XML Free Tutorial

Web based School

XML Document Type Definition


In the previous tutorial, we learned that there are two ways to validate an XML, one of them is XML DTD that can be used to check whether an XML document is “well formed” and “valid”. In this guide, we will learn what is an XML DTD with the help of few examples.
XML DTD
DTD stands for Document Type Definition. An XML DTD defines the structure of an XML document. An XML document is considered “well formed” and “valid” if it is successfully validated against DTD.

An example of DTD
DTD is declared inside definition when the DTD declaration is internal. In this example we can see that there is an XML document that has a definition. The bold part in the following example is the DTD declaration. <?xml version="1.0"?> <!-- XML DTD declaration starts here --> <!DOCTYPE beginnersbook [ <!ELEMENT beginnersbook (to,from,subject,message)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT subject (#PCDATA)> <!ELEMENT message (#PCDATA)> ]> <!-- XML DTD declaration ends here--> <beginnersbook> <to>My Readers</to> <from>Chaitanya</from> <subject>A Message to my readers</subject> <message>Welcome to beginnersbook.com</message> </beginnersbook> Explanation:

!DOCTYPE beginnersbook defines that this is the beginning of the DTD declaration and the root element of this XML document is beginnersbook
!ELEMENT beginnersbook defines that the root element beginnersbook must contain four elements: “to,from,subject,message”
!ELEMENT to defines that the element “to” is of type “#PCDATA” where “#PCDATA” stands for Parsed Character Data which means that this data is parsable by XML parser
!ELEMENT from defines that the element “from” is of type “#PCDATA”
!ELEMENT subject defines that the element “subject” is of type “#PCDATA”
!ELEMENT message defines that the element “message” is of type “#PCDATA”

External DTD Declaration

In the above example, we have internal DTD declaration. Lets see how we can have external DTD declaration in an XML document. For the understanding purpose, lets take the same above example here –
To have the external DTD declaration in an XML document, we must include the reference to the DTD file in the definition, as we have done in the following example.
<?xml version="1.0"?> <!DOCTYPE beginnersbook SYSTEM "bb.dtd"> <beginnersbook> <to>My Readers</to> <from>Chaitanya</from> <subject>A Message to my readers</subject> <message>Welcome to beginnersbook.com</message> </beginnersbook> The <!DOCTYPE> definition in the above document contains the reference to “bb.dtd” file. Here is the content of “bb.dtd” file that contains the DTD for above XML document – <!ELEMENT beginnersbook (to,from,subject,message)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT subject (#PCDATA)> <!ELEMENT message (#PCDATA)>

Previous Next