Monday, July 27, 2009

C# - Validate XML document against a Schema - XmlReaderSettings

Sample code for Validate XML document against a Schema:

...
using System.Xml;
using System.Xml.Schema;
...

public static bool XmlValidateByXsd(string xmlFile, string xsdFile)
{
bool retVal = false;
if( ! File.Exists( xmlFile ) || ! File.Exists( xsdFile ) )
return retVal;

try
{
XmlReaderSettings xmlRdrSettings = new XmlReaderSettings();
xmlRdrSettings.ValidationType = ValidationType.Schema;

xmlRdrSettings.Schemas = new XmlSchemaSet();
xmlRdrSettings.Schemas.Add(null, xsdFile);
xmlRdrSettings.ValidationEventHandler +=
new ValidationEventHandler(ValidationEventHandler);
using (XmlReader xmlRdr = XmlReader.Create(xmlFile, xmlRdrSettings))
{
while (xmlRdr.Read()) { }
}
retVal = true;
}
catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}

return retVal;
}

private static void ValidationEventHandler(object sender, ValidationEventArgs args)
{
// Do error handling
// Console.WriteLine("Error: " + args.Message);
}


The code line to call the method to validate XML against XSD:

bool retVal = myClass.XmlValidateByXsd(@"C:\employee.xml", @"C:\employee.xsd");


Sample XML file:

<?xml version="1.0" standalone="yes"?>
<Employees xmlns="http://iborn2code.blogspot.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://iborn2code.blogspot.com employee.xsd">
<Employee>
<SIN>525252525</SIN>
<FirstName>AB BA</FirstName>
<City>Vancouver</City>
<Zip>V1V</Zip>
</Employee>
<Employee>
<SIN>525252527</SIN>
<FirstName>BC CB</FirstName>
<City>Kelowna</City>
<Zip>V2V</Zip>
</Employee>
</Employees>


Sample XML Schema for above XML:

<div class="mycode">
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="Employee">
<xs:complexType>
<xs:sequence>
<xs:element name="SIN" type="xs:string"/>
<xs:element name="FirstName" type="xs:string"/>
<xs:element name="City" type="xs:string"/>
<xs:element name="Zip" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>
</div>

Share/Bookmark

No comments: