How to validate XML document with XDocument class in VB.NET

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 Sub ValidateHandler(ByVal Sender As Object, ByVal Ev As ValidationEventArgs

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

End Sub

 

Dim XmlFile As String = Server.MapPath(“BooksList.xml”)

Dim XsdFile as String = Server.MapPath(“BooksList.xsd”)

 

‘ Open the XML file.

Dim Doc As XDocument = XDocument.Load(XmlFile)

 

‘ Load the schema.

Dim Schemas As XmlSchemaSet = New XmlSchemaSet()

Schemas.Add(“”, XsdFile);

 

‘ Validate the document (with event handling)

Doc.Validate(schemas, ValidateHandler)