SyntaxStudy
Sign Up
XML Introduction to Document Type Definitions
XML Beginner 1 min read

Introduction to Document Type Definitions

A Document Type Definition (DTD) is a schema language built into the XML specification that allows authors to constrain the structure of an XML document. A DTD declares which elements are permitted, what content each element may contain, and which attributes each element may have. A conforming XML document that satisfies its DTD is called valid. DTDs are declared using a DOCTYPE declaration that can reference an external DTD file, embed the DTD inline, or both. DTDs use their own syntax that is distinct from XML. Element declarations use the keyword, attribute declarations use , entity declarations use , and notation declarations use . Content models in element declarations use sequences (comma-separated), choices (pipe-separated), and cardinality modifiers (? for optional, * for zero-or-more, + for one-or-more). The limitations of DTDs are well known. DTDs do not support XML namespaces natively, they offer limited data typing (only a small set of attribute types such as ID, IDREF, NMTOKEN, and CDATA), and they cannot express constraints like "the value of this attribute must be a positive integer". These limitations led to the development of XML Schema (XSD), RELAX NG, and Schematron as more expressive alternatives. Despite this, DTDs remain important in XHTML, DocBook, and many legacy enterprise systems.
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE library [

    <!-- Root element must contain one or more book elements -->
    <!ELEMENT library (book+)>

    <!-- book contains: title, author+, year, price? -->
    <!ELEMENT book    (title, author+, year, price?)>
    <!ELEMENT title   (#PCDATA)>
    <!ELEMENT author  (#PCDATA)>
    <!ELEMENT year    (#PCDATA)>
    <!ELEMENT price   (#PCDATA)>

    <!--
        ATTLIST for book:
          id        — unique identifier (type ID)
          category  — enumerated value
          available — optional flag, default "true"
    -->
    <!ATTLIST book
        id        ID                        #REQUIRED
        category  (fiction|non-fiction|reference) #REQUIRED
        available (true|false)              "true"
    >

]>
<library>
    <book id="b001" category="non-fiction" available="true">
        <title>XML in a Nutshell</title>
        <author>Elliotte Rusty Harold</author>
        <author>W. Scott Means</author>
        <year>2004</year>
        <price>39.99</price>
    </book>
    <book id="b002" category="reference">
        <title>XML Schema</title>
        <author>Eric van der Vlist</author>
        <year>2002</year>
    </book>
</library>