Sample XML and XSD Files (SAX Validator)

 

[This sample application uses a feature that was first implemented in MSXML 4.0.]

This example attempts to validate an XML data file (books.xml) against an XML schema definition file (books.xsd). According to books.xsd, each <book> element must have a <pub_date> child element. The second <book> element in books.xml does not have this required element. Therefore, when we attempt to validate the XML file , we should get a validation error.

To create books.xsd and books.xml

  1. Open Notepad.

  2. Copy the code for books.xsdand paste it into Notepad.

  3. From Notepad, save the file as books.xsd to the same folder where you are creating the SAX Validator application.

  4. Copy the code for books.xml and paste it in Notepad.

  5. Save the file as books.xml to the same folder where you are creating the SAX Validator application.

XML File (books.xml)

<?xml version="1.0"?>
<x:books xmlns:x="urn:books">
   <book id="bk001">
      <author>Writer</author>
      <title>The First Book</title>
      <genre>Fiction</genre>
      <price>44.95</price>
      <pub_date>2000-10-01</pub_date>
      <review>An amazing story of nothing.</review>
   </book>

   <book id="bk002">
      <author>Poet</author>
      <title>The Poet's First Poem</title>
      <genre>Poem</genre>
      <price>24.95</price>
      <review>Least poetic poems.</review>
   </book>
</x:books>

XSD File (books.xsd)

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="urn:books"
            xmlns:bks="urn:books">

  <xsd:element name="books" type="bks:BooksForm"/>

  <xsd:complexType name="BooksForm">
    <xsd:sequence>
      <xsd:element name="book" 
                  type="bks:BookForm" 
                  minOccurs="0" 
                  maxOccurs="unbounded"/>
      </xsd:sequence>
  </xsd:complexType>

  <xsd:complexType name="BookForm">
    <xsd:sequence>
      <xsd:element name="author"   type="xsd:string"/>
      <xsd:element name="title"    type="xsd:string"/>
      <xsd:element name="genre"    type="xsd:string"/>
      <xsd:element name="price"    type="xsd:float" />
      <xsd:element name="pub_date" type="xsd:date" />
      <xsd:element name="review"   type="xsd:string"/>
    </xsd:sequence>
    <xsd:attribute name="id"   type="xsd:string"/>
  </xsd:complexType>
</xsd:schema>

See Also

Validate Documents Using SAX
Overview of the SAX Validator Application
Application Form (SAX Validator)
MyValidator Class (SAX Validator)
Run the Application (SAX Validator)
How the SAX Validator Application Works