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.
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).
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. |