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">
<Address>123 test dr</Address>
<City>Chevy Chase</City>

Here is sample XSD file:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs=""; targetNamespace="myNamespace" elementFormDefault="qualified">
<xs:element name="Person">
<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" />

Here is C# .NET code to validate XML using XSD file:
private static bool ValidateXmlWithXsd(string xmlUri, string xsdUri)
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

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

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).