Sams Teach Yourself XML in 21 Days

Sams Teach Yourself XML in 21 Days

By Steven Holzner

Creating Valid XML Documents

An XML processor will usually check whether your XML document is well-formed, but only some are also capable of checking whether it's valid. An XML document is valid if it adheres to the syntax you've specified for it, and you can specify that syntax in either a Document Type Definition ( DTD ) or an XML schema. We'll see DTDs in Days 4 and 5, and XML schemas in Days 6 and 7.

As an example, you can see how you add a DTD to our XML document in Listing 1.7. DTDs can be separate documents, or they can be built into an XML document as we've done here using a special element named <!DOCTYPE>.

Example 1.7. An XML Document with a DTD (ch01_07.xml)

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="ch01_04.css"?>
<!DOCTYPE DOCUMENT [

       <!ELEMENT document (heading, message)>

       <!ELEMENT heading (#PCDATA)>

       <!ELEMENT message (#PCDATA)>

   ]>
<document>
    <heading>
        Hello From XML
    </heading>
    <message>
        This is an XML document!
    </message>
</document>

We'll create DTDs like this one in Day 4, "Creating Valid XML Documents: Document Type Definitions"; briefly, the DTD in Listing 1.7 is the <!DOCTYPE> element, which specifies that the root element, <document>, should contain a <heading> element and a <message> element. We're also specifying that the <heading> and <message> elements may contain text data. Using a DTD like this, you're able to specify the syntax your XML document should obey—what elements should be inside what other elements, what attributes an element can have, and so on—and if an XML processor can perform validation, it can check your document and head off problems (we'll validate this document tomorrow).

Today's discussion has introduced us to the basic XML concepts that we'll need for the coming days. Now it's time to start taking an in-depth look at how XML is used in the real world and what it's good for.

Share ThisShare This

Informit Network