ISSUE :
 
Profile photo
Submitted by Dave Smith
on June 6th, 2011 at 08:06:42 EST

How to validate XML using schema (XSD) in C# .NET?

I created a schema (XSD) for my XML file. During runtime I need to validate if the XML file is valid based on the schema that I created. Is there any way in .NET to validate XML file against schema (XSD) file? I am using C#.


Profile photo
Replied by SBajra
on June 6th, 2011 at 21:58:04 EST
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;
}
}
Accepted Answer
Accepted
 Answer

Profile photo
Replied by Dave Smith
on June 6th, 2011 at 22:32:42 EST
Thanks for detail explanation.

Profile photo
Replied by Megha Shedligeri
on April 14th, 2012 at 13:02:23 EST
Hi,

I am validating xml files using a schema through the code you have mentioned above
in my program but what I don't understand is the need to add such a validation code in my program cos in visual studio if you add the xml schema namespace in the xml ,it will automatically validate it at runtime .so what is the need for validating through the code ?

Thanks In Advance

Profile photo
Replied by SBajra
on April 15th, 2012 at 20:55:11 EST
This dynamic XML validation is useful when you get XML from external source and you want to validate the XML using the schema (XSD).