How to validate XML document with XDocument class in C#

When you want to validate an XML document against a schema, by using XDocument you need to import the System.Xml.Schema namespace. In this way you can use validation classes which XDocument class doesn’t have. The imported namespace contains an Extensions class that include a Validate() method you can use on an XElement or XDocument.

Note: You can find more details about XML schemas from the article How to use XML Schemas in XML document.

 

Here’s an example that uses the Validate() extension method to validate the BooksList.xml document:

 

public void ValidateHandler(Object sender, ValidationEventArgs e)

{

lblStatus.Text += “Error: ” + e.Message + “<br>”;

}

 

 

string xmlFile = Server.MapPath(“BooksList.xml”);

string xsdFile = Server.MapPath(“BooksList.xsd”);

 

// Open the XML file.

XDocument doc = XDocument.Load(xmlFile);

 

// Load the schema.

XmlSchemaSet schemas = new XmlSchemaSet();

schemas.Add(“”, xsdFile);

 

// Validate the document (with event handling

doc.Validate(schemas, ValidateHandler);