Java Reference
In-Depth Information
<!ELEMENT library (book+)>
<!ELEMENT book (title,author+,price)>
<!ATTLIST book
isbn CDATA #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
The idea is that a library element contains one or more book s. A book element con-
tains a title , one or more author elements, and a price , in that order. The book
element has an attribute called isbn , which is a simple string but is required. The title ,
author , and price elements all consist of simple strings.
To tie the XML file to the DTD, I add the following line before the root element:
<!DOCTYPE library SYSTEM "library.dtd">
Validating the XML file against the DTD is then almost trivial. The XmlSlurper class
has an overloaded constructor that takes two arguments, both of which are Booleans. The
first is to trigger validation, and the second is namespace awareness. Namespaces aren't
relevant when discussing a DTD, but it doesn't hurt to turn on both properties:
def root = new XmlSlurper(true, true).parse(fileName)
That'sallthat'sneededtodothevalidation.IftheXMLdatadoesn'tsatisfytheDTD,errors
will be reported by the parsing process.
Validation against an XML schema has always been more of a challenge. Schemas un-
derstand namespaces and namespace prefixes, and there are many things you can do in a
schema that you can't do in a DTD.
Consider the next listing, which shows a schema for the library.
Listing B.7. An XML schema for the library XML
<?xml version= "1.0" encoding= "UTF-8" ?>
<schema
xmlns= "http://www.w3.org/2001/XMLSchema"
targetNamespace= "http://www.kousenit.com/books"
xmlns:tns= "http://www.kousenit.com/books"
elementFormDefault= "qualified" >
Search WWH ::




Custom Search