- 64 -
Figure 3.8:
Parser output of CDATA snippet.
Document Type Declaration
A
document type declaration
is a statement embedded in an XML document whose
purpose is to herald the existence and location of a document type definition (DTD).
Read that statement twice. A
document type
declaration
is different from a document
type
definition
. The first is a statement that points to the second. A DTD is a set of rules
that defines the structure of an XML document. A document
type declaration is a
statement that tells the parser which DTD to use for checking and validation.
Let’s say we have an XML document called myfile.xml that we want the parser to validate
against a DTD called my_rules.dtd. The way to associate (that is, tell the parser to check)
the content structure of myfile.xml against the rules specified in my_rules.dtd is to insert
the following line after the XML declaration:
The above simply states that
for this particular document, whose root element’s name is
myfile (note: the root element name MUST match the root element declared in the
declaration), a DTD is available, and its name and path is my_rules.dtd.
Intuitive, isn’t it?
Seriously though, now you have a glimpse as to why we detest DTDs so much.
Document Type Declarations can have external and internal components; that is, they
can refer to Document Type
Definitions
that are either declared within
the XML document
itself (so the structural rules are contained within the XML document itself) or described in
an external file/location (that is, it points to an external document that contains structural
information
about the document, just as a model number refers to specifications
contained in an external manual).
If the DTDs are internal, the syntax to use is this:
]>
Even though we’re getting ahead of ourselves (internal subsets
are discussed later on in
this chapter), here’s an example of an internal subset declaration and its usage:
]>
- 65 -
Alex, Faraz
Similarly, for external subsets, the syntax found in the XML document is:
...
To exemplify this, we need to have two documents: the
external DTD and the XML
document. The XML document looks like this:
Alex, Faraz
while the DTD, good_guys.dtd looks like this:
A document can have
both
internal and external document type declarations so that you
can further define your structure. In keeping
with the same theme as above, our
good_guys.dtd should look like this:
If we further wanted to define the structure of our good_guy element, our good_guys.xml
XML file could look like this:
]>
Alex, Faraz
Hold on to your hats; it gets worse before it gets better. But rest assured—it does get
better!