DTD Elements
Creating a DTD is quite straight forward. It's really just a matter of defining your elements, attributes, and/or entities. Over the next few lessons, I'll explain how to define your elements, attributes, and entities.
In this lesson, we'll look at the syntax for defining your XML elements.
To define an element in your DTD, you use the <!ELEMENT>
declaration. The actual contents of your <!ELEMENT>
declaration will depend on the syntax rules you need to apply to your element.
Basic Syntax
The <!ELEMENT>
declaration has the following syntax:
Here, element_name
is the name of the element you're defining. The content model
could indicate a specific rule, data or another element.
- If it specifies a rule, it will be set to either
ANY
orEMPTY
. - If specifies data or another element, the data type/element name needs to be surrounded by brackets (i.e.
(tutorial)
or(#PCDATA)
).
The following examples show you how to use this syntax for defining your elements.
Plain Text
If an element should contain plain text, you define the element using #PCDATA. PCDATA stands for Parsed Character Data and is the way you specify non-markup text in your DTDs.
Using this example - <name>XML Tutorial</name>
— the XML Tutorial
part is the PCDATA. The other part consists of markup.
Syntax:
Example:
The above line in your DTD allows the name
element to contain non-markup data in your XML document:
Unrestricted Elements
If it doesn't matter what your element contains, you can create an element using the content_model of ANY
. Note that doing this removes all syntax checking, so you should avoid using this if possible. You're better off defining a specific content model.
Syntax:
Example:
Empty Elements
You might remember that an empty element is one without a closing tag. For example, in XHTML, the <br />
and <img />
tags are empty elements. Here's how you define an empty element:
Syntax:
Example:
The above line in your DTD defines the following empty element for your XML document:
Child Elements
You can specify that an element must contain another element, by providing the name of the element it must contain. Here's how you do that:
Syntax:
Example:
The above line in your DTD allows the tutorials
element to contain one instance of the tutorial
element in your XML document:
Multiple Child Elements (Sequences)
You can also provide a comma separated list of elements if it needs to contain more than one element. This is referred to as a sequence. The XML document must contain the tags in the same order that they're specified in the sequence.
Syntax:
Example:
The above line in your DTD allows the tutorial
element to contain one instance of the name
element and one instance of the url
element in your XML document: