Whenever you ask user to provide XML file as input, you will expect it in some format. To check whether that input XML file is in correct format or not, you have to validate it against some predefined format.
In C#, we can validate the XML file against XSD file where you have to define required format. So, whenever user uploads XML file it has to be validate through this XSD format to check whether it is in correct format or not.
For example we have Employees.xml file as shown below.
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee>
<Id>1</Id>
<Name>A</Name>
</Employee>
<Employee>
<Id>2</Id>
<Name>B</Name>
</Employee>
<Employee>
<Id>3</Id>
<Name>C</Name>
</Employee>
<Employee>
<Id>4</Id>
<Name>D</Name>
</Employee>
</Employees>
To validate this XML file we defined the XSD format as shown below.
<xsd:schema id="Employees" elementFormDefault="qualified"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
>
<xsd:element name="Employees" type="EmployeesType"/>
<xsd:complexType name="EmployeesType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="Employee" type="EmployeeType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="EmployeeType">
<xsd:sequence>
<xsd:element name="Id" type="xsd:string"/>
<xsd:element name="Name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
We have input XML file and required XSD format. Now we have to validate that XML file through this XSD format. For this we have two namespaces in C#, those are System.Xml and System.Xml.Schema. We validate XML input in C# as shown below.
using System;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Schema;
namespace CompareXMLSchema
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ValidationCallBack(object sender, ValidationEventArgs e)
{
throw new Exception();
}
public bool Validate(string sXMLPath,string sXSDPath)
{
try
{
XmlDocument xmld = new XmlDocument();
xmld.Load(sXMLPath);
xmld.Schemas.Add(null, sXSDPath);
xmld.Validate(ValidationCallBack);
return true;
}
catch (Exception ex)
{
return false;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (Validate("../../Employees.xml", "../../Employees.xsd"))
{
MessageBox.Show("Input XML File is in correct format only");
}
else
{
MessageBox.Show("Input XML File is not in correct format");
}
}
}
}
As shown above whenever user clicks on button we call the Validate() method. In Validate() method we will validate the input XML file against predefined XSD schema by using XmlDocument Validate() method. ValidationCallback() method is the call back method which executes whenever there is a error in XML file while validating against XSD schema.
To test try to add extra element to Employees.xml file and click on button, it displays error message as "Input XML File is not in correct format".