You can validate XML using XSD using XmlReader class with XmlReaderSettings.
For example:
Here is sample XML file:
<?xml version="1.0" encoding="utf-8" ?>
<Person xmlns="myNamespace">
<Name>John</Name>
<Address>123 test dr</Address>
<City>Chevy Chase</City>
<State>MD</State>
<Zip></Zip>
</Person>
Here is sample XSD file:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myNamespace" elementFormDefault="qualified">
<xs:element name="Person">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" />
<xs:element name="Address" type="xs:string" />
<xs:element name="City" type="xs:string" />
<xs:element name="State" type="xs:string" />
<xs:element name="Zip" type="xs:integer" nillable="false" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Here is C# .NET code to validate XML using XSD file:
private static bool ValidateXmlWithXsd(string xmlUri, string xsdUri)
{
try
{
XmlReaderSettings xmlSettings = new XmlReaderSettings();
xmlSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
xmlSettings.Schemas.Add("myNamespace", xsdUri);
xmlSettings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(xmlUri, xmlSettings);
// Parse the file.
while (reader.Read()) ;
return true;
}
catch(Exception ex)
{
return false;
}
}