You can validate an XML document against a schema, by using built in XmlReader’s validation features. Note: You can find more details about XML schemas from the article How to use XML Schemas in XML document.  You can follow the next steps when performing validation:

1. You need to import the System.Xml.Schema namespace, which contains types such as XmlSchema and XmlSchemaCollection:

Imports System.Xml.Schema

2. You need to create the validation reader, by using XmlReaderSettings object that specifically indicates that you want to perform validation. You can do this by setting the ValidationType property and loading your XSD schema file into the Schemas collection, as shown here:

 

‘ Configure the reader to use validation.

Dim Settings As XmlReaderSettings = New XmlReaderSettings()

Settings.ValidationType = ValidationType.Schema

 

‘ Create the path for the schema file.

Dim schemaFile As String = Path.Combine(Request.PhysicalApplicationPath, “App_Data\BooksList.xsd”);

 

‘ Indicate that elements in the namespace

‘ https://www.Books.com/BooksList should be validated using the schema file.

Settings.Schemas.Add(“urn:books”,SchemaFile);

 

3. You need to create the validation reader, by using the static XmlReader.Create() method. This method has several overloads, but you can use  a FileStream (with the XML document) and the XmlReaderSettings object that has your validation settings:

 

‘ Open the XML file.

Dim Fs As FileStream = New FileStream(File, FileMode.Open)

 

‘ Create the validating reader.

Dim R As XmlReader = XmlReader.Create(Fs, Settings)

 

The XmlReader in this example works in the same way as is explained in the articles How to use XmlTextReader to read XML file as text in VB.NET or How to use XmlTextReader to read XML file as objects in VB.NET, but it adds the ability to verify that the XML document follows the schema rules. This reader throws an exception (or raises an event) to indicate errors as you move through the XML file.

The following example shows how you can create a validating reader that uses the BooksList.xsd file to verify that the XML in BooksList.xml is valid:

 

Imports System.Collections.Generic

Imports System.Linq

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.IO

Imports System.Xml

Imports System.Xml.Schema

 

Public Class XMLValidator

Inherits System.Web.UI.Page

 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not Me.IsPostBack Then

XMLValidator()

End If

End Sub

 

Protected Sub XMLValidator()

 

‘ Configure the reader to use validation.

Dim Settings As XmlReaderSettings = New XmlReaderSettings()

Settings.ValidationType = ValidationType.Schema

 

‘ Create the path for the schema file.

Dim SchemaFile As String = Path.Combine(Request.PhysicalApplicationPath, “App_Data\BooksList.xsd”)

 

‘Indicate that elements in the namespace

‘ https://www.Books.com/BooksList should be validated using the schema file.

Settings.Schemas.Add(“urn:books”, SchemaFile)

Settings.ValidationFlags = Settings.ValidationFlags Or XmlSchemaValidationFlags.ProcessInlineSchema

Settings.ValidationFlags = Settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings

 

‘ Open a stream to the file.

Dim File As String = Path.Combine(Request.PhysicalApplicationPath, “App_Data\BooksList.xml”)

Dim Fs As New FileStream(File, FileMode.Open)

Dim R As XmlReader = XmlReader.Create(Fs, Settings)

 

‘ Create a generic collection of books.

Dim Books As New List(Of Book)()

‘ Loop through the books.

LblStatus.Text = “”

While R.Read()

If R.NodeType = XmlNodeType.Element AndAlso R.Name = “Book” Then

Dim newBook As New Book()

newBook.Isbn13 = R.GetAttribute(“ISBN-13”)

newBook.Title = R.GetAttribute(“Title”)

‘ Get the rest of the subtags for this book

While R.NodeType <> XmlNodeType.EndElement

R.Read()

‘ Look for Author subtags.

If R.Name = “Author” Then

While R.NodeType <> XmlNodeType.EndElement

R.Read()

If R.NodeType = XmlNodeType.Text Then

newBook.Author = R.Value

End If

End While

End If

R.Read()

If R.Name = “Price” Then

While R.NodeType <> XmlNodeType.EndElement

R.Read()

If R.NodeType = XmlNodeType.Text Then

newBook.Price = Decimal.Parse(R.Value)

End If

End While

End If

R.Read()

If R.Name = “Available” Then

While R.NodeType <> XmlNodeType.EndElement

R.Read()

If R.NodeType = XmlNodeType.Text Then

newBook.Available = Boolean.Parse(R.Value)

End If

End While

End If

End While

Books.Add(newBook)

End If

End While

‘ end of while

Fs.Close()

If (Not LblStatus.Text.Contains(“Error”)) Then

GridResult.DataSource = Books

GridResult.DataBind()

End If

End Sub

End Class

 

 

Using the current file, this code will succeed, and you’ll be able to access each node in the document. However, consider what happens if you make the minor modification shown here:

 

<Author>J.K. Rowling</Author>

<Price>1x.99</Price>

 

Now when you try to validate the document, an XmlSchemaException (from the System.Xml.Schema namespace) will be thrown, alerting you to the invalid data type, as shown in:

 

Validating of an XML document with XML Schemas in VB.NET

Validating of an XML document with XML Schemas in VB.NET

Instead of catching errors, you can react to the XmlReaderSettings.ValidationEventHandler event. If you react to this event, you’ll be provided with information about the error, but no exception will be thrown. To connect an event handler to this event, you can attach an event handler before you create the XmlReader:

 

‘ Connect to the method named ValidateHandler.

AddHandler Settings.ValidationEventHandler, AddressOf ValidateHandler

The event handler receives a ValidationEventArgs object as a parameter, which contains the exception, a message, and a number representing the severity:

 

Public Sub ValidateHandler(sender As Object, args As ValidationEventArgs)

If (args.Severity = XmlSeverityType.Error) Then

LblStatus.Text += “Error: ” + ”   Validation error: ” + args.Message

End If

End Sub

The next picture shows the result of failed validation attempt:

 

Using of event handler in XML document validation against XML schema in VB.NET

Using of event handler in XML document validation against XML schema in VB.NET