SUMMARY
This step-by-step article describes how to use
XmlValidatingReader and
XMLSchemaCollection objects to validate an Extensible Markup Language (XML) fragment
against an XML schema.
XmlValidatingReader implements the
XmlReader class and provides support for XML data validation. The
Schemas property of
XmlValidatingReader connects the reader to the schema files cached in an
XmlSchemaCollection. The
ValidationType property of
XmlValidatingReader specifies the type of validation the reader should perform. If
you set the property to
ValidationType.None, you create a nonvalidating reader.
You can only add
XML Schema Definition Language (XSD) schemas and XML-Data Reduced (XDR) schemas
to
XmlSchemaCollection. Use the
Add method with a namespace URI to load schemas. For XML schemas, the
typical namespace URI is the
targetNamespace property of the schema.
back to the top
Requirements
The following list outlines the recommended hardware, software,
network infrastructure, and service packs that you will need:
- Microsoft Visual Studio .NET installed on a compatible
Microsoft Windows operating system
This article assumes that you are familiar with the following
topics:
- Visual Basic .NET
- Basic XML standards
- XSD schemas
back to the top
Create an XSD Schema
Paste the following code in a new text file named C:\Books.xsd:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:bookstore-schema" elementFormDefault="qualified" targetNamespace="urn:bookstore-schema">
<xsd:element name="bookstore" type="bookstoreType" />
<xsd:element name="comment" type="xsd:string" />
<xsd:element name="author" type="authorName"/>
<xsd:complexType name="authorName">
<xsd:sequence>
<xsd:element name="first-name" type="xsd:string" />
<xsd:element name="last-name" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="book" type="bookType" />
<xsd:element ref="comment" minOccurs="0" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bookType">
<xsd:sequence>
<xsd:element name="title" type="xsd:string" />
<xsd:element ref="author" />
<xsd:element name="price" type="xsd:decimal" />
</xsd:sequence>
<xsd:attribute name="genre" type="xsd:string" />
</xsd:complexType>
</xsd:schema>
back to the top
Create a Visual Basic .NET Application
- Create a new Visual Basic .NET Windows
application.
- Drag Button1 to Form1. Paste the following code to add a private member
variable to Class Form1:
Dim m_success As Boolean
- Paste the following sub procedure to create a ValidationEventHandler that raises validation errors in the XMLValidatingReader object:
Public Sub ValidationEventHandle(ByVal sender As Object, ByVal args As ValidationEventArgs)
m_success = False
Console.WriteLine((ControlChars.CrLf & ControlChars.Tab & "Validation error: " & args.Message))
End Sub 'ValidationEventHandle
NOTE: You must include an event handler to receive information about
validation errors in the Data Type Definition (DTD), the XML-Data Reduced (XDR)
schema, and the XML schema definition language (XSD) schema. The event handler
receives an argument of type ValidationEventArgs that contains data related to this event.
The callback
handler can use the ValidationEventArgs.Severity property to guarantee that an XML instance document is validated
against a schema. The Severity property enables you to distinguish between a validation error (Severity is equal to XmlSeverityType.Error) which indicates a fatal error, and a validation warning (Severity is equal to XmlSeverityType.Warning) which indicates that no schema information is
available. - Paste the following code in the Button1_Click event procedure:
Dim reader As XmlValidatingReader = Nothing
Dim myschema As New XmlSchemaCollection()
Try
'Create the XML fragment to be parsed.
Dim xmlFrag As String = "<author xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" & _
"<first-name>Herman</first-name>" & _
"<last-name>Melville</last-name>" & _
"</author>"
'Create the XmlParserContext.
Dim context As New XmlParserContext(Nothing, Nothing, "", XmlSpace.None)
'Implement the reader.
reader = New XmlValidatingReader(xmlFrag, XmlNodeType.Element, context)
'Add the schema.
myschema.Add("urn:bookstore-schema", "Books.xsd")
'Set the schema type and add the schema to the reader.
reader.ValidationType = ValidationType.Schema
reader.Schemas.Add(myschema)
'Add the handler to raise the validation event.
AddHandler reader.ValidationEventHandler, AddressOf Me.ValidationEventHandle
While reader.Read
End While
Console.WriteLine("Completed validating xmlfragment")
Catch XmlExp As XmlException
Console.WriteLine(XmlExp.Message)
Catch XmlSchExp As XmlSchemaException
Console.WriteLine(XmlSchExp.Message)
Catch GenExp As Exception
Console.WriteLine(GenExp.Message)
End Try
End Sub
- When the following message is displayed in the output
window, the XML fragment is a valid element:
Completed validating xmlfragment
NOTE: The
XMLValidatingReader object validates only the type declarations and the top level
elements in the XML Schema. XML fragments, such as sub elements, are considered
to be local. You cannot pass XML fragments to
XmlValidatingReader for direct validation unless you declare the XML fragments as
top-level elements and set the reference at the required level.
back to the top
REFERENCES
For additional
information, click the article numbers below to view the articles in the
Microsoft Knowledge Base:
307379 HOW TO: Validate an XML Document by Using DTD, XDR, or XSD in Visual C# .NET
313826 INFO: Roadmap for XML Schemas in the .NET Framework
313651 INFO: Roadmap for XML in the .NET Framework
For additional information, see the following MSDN
Web sites:
back to the top