Resource: books.xml and books.xsd
This example uses two resources files. One is an XML data file (books.xml) and the other is an XML Schema definition file (books.xsd). According to books.xsd, the second <book>
element in books.xml is missing the required <pub_date>
child element. Therefore, when we attempt to validate the XML file against the given schema, we get a validation error.
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>
To add books.xml and books.xsd to the project
- Create a new text file in the project's main working directory using Notepad or another text editor. Name the new file books.xml.
- Copy books.xml, above, and paste it into the empty text file you just created.
- Create a new text file in the project's main working directory using Notepad or another text editor. Name the new file books.xsd.
- Copy books.xsd, above, and paste it into the empty text file you just created.
Next, run the project. The result should be the output shown in the following topic.