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

Article translations Article translations
Article ID: 317463 - View products that this article applies to.
This article was previously published under Q317463
Expand all | Collapse all

On This Page

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.

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

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>
				

Create a Visual Basic .NET Application

  1. Create a new Visual Basic .NET Windows application.
  2. Drag Button1 to Form1. Paste the following code to add a private member variable to Class Form1:
    Dim m_success As Boolean
    					
  3. 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.
  4. 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
    					
  5. 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.

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:
System.Xml Namespace
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxml.asp

XML Web Services
http://msdn.microsoft.com/xml

Properties

Article ID: 317463 - Last Review: September 3, 2003 - Revision: 2.2
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
Keywords: 
kbhowtomaster KB317463

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com