programming4us
programming4us
WEBSITE

ASP.NET 4 in VB 2010 : XML Validation (part 2) - Validating an XML Document

4/4/2013 3:34:27 AM

3. Validating an XML Document

The following example shows you how to validate an XML document against a schema, using an XmlReader that has validation features built in.

The first step when performing validation is to import the System.Xml.Schema namespace, which contains types such as XmlSchema and XmlSchemaCollection:

Imports System.Xml.Schema

You must perform two steps to create the validating reader. First, you create an XmlReaderSettings object that specifically indicates you want to perform validation. You 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 New XmlReaderSettings()
settings.ValidationType = ValidationType.Schema

' Create the path for the schema file.
Dim schemaFile As String = Path.Combine(Request.PhysicalApplicationPath, _
  "App_Data\SuperProProductList.xsd")

' Indicate that elements in the namespace
' http://www.SuperProProducts.com/SuperProProductList should be
' validated using the schema file.
settings.Schemas.Add("http://www.SuperProProducts.com/SuperProProductList", _
  schemaFile)

					  

Second, you need to create the validating reader using the shared XmlReader.Create() method. This method has several overloads, but the version used here requires a FileStream (with the XML document) and the XmlReaderSettings object that has your validation settings:

' Open the XML file.
Dim fs As 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 the XmlTextReader you've been using up until now, 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 SuperProProductList.xsd file to verify that the XML in SuperProProductList.xml is valid:

' Set the validation settings.
Dim settings As New XmlReaderSettings()
settings.Schemas.Add("http://www.SuperProProducts.com/SuperProProductList", _
  schemaFile)
settings.ValidationType = ValidationType.Schema

' Open the XML file.
Dim fs As New FileStream(file, FileMode.Open)

' Create the validating reader.
Dim r As XmlReader = XmlReader.Create(fs, settings)

' Read through the document.
Do While r.Read()
    ' Process document here.
    ' If an error is found, an exception will be thrown.
Loop
fs.Close()

					  

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:

<Product ID="A" Name="Chair">

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 Figure 1.

Figure 1. An XmlSchemaException

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:

Private Sub ValidateHandler(ByVal sender As Object, _
  ByVal e As ValidationEventArgs)
    lblStatus.Text &= "Error: " & e.Message & "<br />"
End Sub

To test the validation, you can use the XmlValidation.aspx page in the online samples. It allows you to validate a valid SuperProProductList, as well as two other versions, one with incorrect data and one with an incorrect element (see Figure 2).

Figure 2. The validation test page

Because all XmlReader objects process XML one line at a time, this validation approach performs the best and uses the least amount of memory. But if you already have an XDocument in memory, you can validate it in a similar way using the XDocument.Validate() method.

Other  
 
video
 
Video tutorials
- How To Install Windows 8

- How To Install Windows Server 2012

- How To Install Windows Server 2012 On VirtualBox

- How To Disable Windows 8 Metro UI

- How To Install Windows Store Apps From Windows 8 Classic Desktop

- How To Disable Windows Update in Windows 8

- How To Disable Windows 8 Metro UI

- How To Add Widgets To Windows 8 Lock Screen

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010
programming4us programming4us
programming4us
 
 
programming4us