The Fundamentals of DTD Design - Rainy Days (Page 3 of 8 )
Once you have an XML document and a DTD linked together, an XML parser can verify the document against the DTD and let you know if it finds errors. A number of tools are available online to perform this validation - my favourite is the XML Spy editor, available at http://www.xmlspy.com/ , although you can also try out expat, at
http://sourceforge.net/projects/expat/, and rxp, at
http://www.cogsci.ed.ac.uk/~richard/rxp.html Here's what rxp has to say when I run it on the XML document above.
$ rxp -V weather.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE weather
SYSTEM "weather.dtd">
<weather>
<city>New York</city>
<high>26</high>
<low>18</low>
<forecast>rain</forecast>
</weather>
In other words - no error.
Let's suppose I altered the XML document instance a little, by modifying one of the element names and adding a new element.
<?xml version="1.0"?>
<!DOCTYPE weather SYSTEM "weather.dtd">
<weather>
<city>New
York</city>
<high>26</high>
<low>18</low>
<weekly_mean>21</weekly_mean>
<daily_forecast>rain</daily_forecast>
</weather>
While this version of the document is still well-formed, it no longer follows
the rules laid down in "weather.dtd" and hence cannot be considered valid - which is why rxp barfs and generates a list of errors.
$ rxp -V weather.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE weather
SYSTEM "weather.dtd">
<weather>
<city>New York</city>
<high>26</high>
<low>18</low>
Warning: Start tag
for undeclared element weekly_mean
in unnamed entity at line 7 char 14 of weather.xml
Warning:
Content model for weather does not allow element weekly_mean here
in unnamed
entity at line 7 char 14 of weather.xml
<weekly_mean>21</weekly_mean>
Warning: Start tag for undeclared element daily_forecast
in unnamed entity
at line 8 char 17 of weather.xml
<daily_forecast>rain</daily_forecast>
</weather>
Incidentally, it's also possible to place the DTD within the XML document itself.
Although this is quite rare - the DTD is usually stored in a central place so that it can be referenced by different XML documents - you should know how to do it in case you're ever home on a Saturday evening and feel like experimenting.
<?xml version="1.0"?>
<!DOCTYPE weather [
<!ELEMENT weather (city,
high, low, forecast)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT high (#PCDATA)>
<!ELEMENT
low (#PCDATA)>
<!ELEMENT forecast (#PCDATA)>
]>
<weather>
<city>New
York</city>
<high>26</high>
<low>18</low>
<forecast>rain</forecast>
</weather>
Next: Simply Elementary >>
More XML Articles
More By Vikram Vaswani, (c) Melonfire