Declaring Elements in DTD
An element declaration is used in DTD to describe what content, child element(s), and attribute(s), that element can contain. One element declaration is used for each element within an XML document, separately. We begin with the declaration of the root element in our XML file.
<!ELEMENT article (title, author, body)>
Above DTD element declaration states that there must be a root element with the name of "article" and that element must have child elements with the names of "title", "author" and "body", in that order.
Each element that has been referenced by name in the above declaration, now must have its own separate declaration.
<!ELEMENT article (title, author, body)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT body (#PCDATA)>
Above element declarations that follow the root element declaration ("article") state that these elements can contain character data.
If you want to have the option where you do not put "author" element within an XML document, all you have to do is to put a '?' (question mark) in front of the "author" reference like this:
<!ELEMENT article (title, author?, body)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT body (#PCDATA)>
A '?' (question mark) in front of an element reference means that, that element can be present zero or one time. Now, an XML document without any "author" element (but with article, title and body elements in proper order) can still be a validated successfully
Associating DTD with XML Documents
1:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article SYSTEM "article.dtd"
<article>
<title>Sample XML Document.</title>
<author email="hidden@xyz.com">Faisal Khan</author>
<body>This is a sample XML Document.</body>
</article>
2:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article [
<!ELEMENT article (title, author?, body)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT body (#PCDATA)>
<!ATTLIST author email CDATA #REQUIRED>
]>
<article>
<title>Sample XML Document.</title>
<author email="hidden@xyz.com">Faisal Khan</author>
<body>This is a sample XML Document.</body>
</article>