Microsoft KB Archive/317463

= HOW TO: Validate XML Fragments Against an XML Schema in Visual Basic .NET =

Article ID: 317463

Article Last Modified on 9/3/2003

-

APPLIES TO


 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft .NET Framework 1.1
 * Microsoft .NET Framework 1.0

-



This article was previously published under Q317463



The following .NET Framework Class Library namespaces are referenced in this article: System.XML For a Microsoft Visual C# .NET version of this article, see 318504.

IN THIS TASK
SUMMARY
 * Requirements
 * Create an XSD Schema
 * Create a Visual Basic .NET Application

REFERENCES



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:element ref=&quot;comment&quot; minOccurs=&quot;0&quot; /> </xsd:sequence> </xsd:complexType> <xsd:complexType name=&quot;bookType&quot;>  <xsd:element name=&quot;title&quot; type=&quot;xsd:string&quot; /> <xsd:element ref=&quot;author&quot; /> <xsd:element name=&quot;price&quot; type=&quot;xsd:decimal&quot; /> </xsd:sequence> <xsd:attribute name=&quot;genre&quot; type=&quot;xsd:string&quot; /> </xsd:complexType> </xsd:schema> back to the top

Create a Visual Basic .NET Application
<ol> <li>Create a new Visual Basic .NET Windows application.</li> <li> Drag Button1 to Form1. Paste the following code to add a private member variable to Class Form1: Dim m_success As Boolean </li> <li> 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 & &quot;Validation error: &quot; & 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. </li> <li> 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 = &quot;<author xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>&quot; & _ &quot;<first-name>Herman</first-name>&quot; & _ &quot;<last-name>Melville</last-name>&quot; & _ &quot; &quot;

'Create the XmlParserContext. Dim context As New XmlParserContext(Nothing, Nothing, &quot;&quot;, XmlSpace.None) 'Implement the reader. reader = New XmlValidatingReader(xmlFrag, XmlNodeType.Element, context) 'Add the schema. myschema.Add(&quot;urn:bookstore-schema&quot;, &quot;Books.xsd&quot;)

'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(&quot;Completed validating xmlfragment&quot;)

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 </li> <li> When the following message is displayed in the output window, the XML fragment is a valid element: <pre class="fixed_text">Completed validating xmlfragment </li></ol>

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

<div class="references_section">