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.

C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development: Build applications with C#, .NET Core, Entity Framework Core, ASP.NET Core, and ML.NET using Visual Studio Code, 4th Edition
ASP.NET Core 3 and Angular 9: Full stack web development with .NET Core 3.1 and Angular 9, 3rd Edition
C# in Depth, 4th Edition

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)