Sams Teach Yourself XML in 21 Days

Sams Teach Yourself XML in 21 Days

By Steven Holzner

Validating a Document by Using a DTD

Before you create DTDs of the kind shown in ch04_01.xml (refer to Listing 4.1), let's take a look at how to use DTDs to check an XML document's validity by using an XML validator. We discussed and used XML validators on Day 1, "Welcome to XML," and that discussion provides a list of online XML validators that make use of DTDs. One of the easiest to use is the Scholarly Technology Group's XML validator at Brown University, http://www.stg.brown.edu/service/xmlvalid; although it's online, it lets you browse to XML documents on your hard drive to check them. Figure 4.1 shows the results of validating today's first DTD example, ch04_01.xml; as we can see, the document validates correctly.

04fig01.gif

Figure 4.1 Validating an XML document by using a DTD.

On the other hand, say that our data-entry team made a mistake and someone typed <nane> instead of <name> in an element:

<document>
    <employee>
        <nane>
            <lastname>Kelly</lastname>
            <firstname>Grace</firstname>
        </name>
        <hiredate>October 15, 2005</hiredate>
        <projects>
            <project>
                <product>Printer</product>
                <id>111</id>
                <price>$111.00</price>
            </project>
            <project>
                <product>Laptop</product>
                <id>222</id>
                <price>$989.00</price>
            </project>
        </projects>
    </employee>
        .
        .
        .

This error would not be easy to catch if you were trying to check all 5,000 employee records by eye, but it's no problem at all for an XML validator. Figure 4.2 shows how the Scholarly Technology Group's XML validator catches this error and others.

04fig02.gif

Figure 4.2 Catching an error in an XML document by using a DTD.

Let's start creating DTDs like the one shown in ch04_01.xml. You've seen that a DTD goes in a <!DOCTYPE> element, but what does the actual DTD itself look like? The first step in creating that DTD is to declare the elements that appear in the XML document, as described in the following section.

Share ThisShare This

Informit Network