SyntaxStudy
Sign Up
XML DTD Attribute Types and Defaults
XML Beginner 2 min read

DTD Attribute Types and Defaults

DTDs support several attribute types that provide basic validation beyond simple text strings. CDATA means any character data — no further validation. NMTOKEN restricts the value to an XML name token (no spaces, starts with a letter or digit or selected punctuation). NMTOKENS is a whitespace-separated list of NMTOKENs. Enumerated types restrict the value to one of a parenthesized set of NMTOKENs, like (red|green|blue). ID declares a unique document-wide identifier, IDREF references an existing ID, and IDREFS is a whitespace-separated list of IDREFs. Attribute defaults come in four forms. #REQUIRED means the attribute must always be present in the document. #IMPLIED means the attribute is optional with no default value. A quoted string like "true" provides a default value used when the attribute is absent — the parser supplies this value automatically. #FIXED "value" means the attribute must either be absent or equal to the fixed value; if absent, the parser supplies it; if present, the value must match. The ID/IDREF mechanism provides a simple cross-reference system within a DTD. An element with an ID-typed attribute can be referenced from another element's IDREF attribute, creating a logical link. Processors that handle this mechanism can use it to locate elements by their ID value using the element() XPath function or the getElementById() DOM method. However, this mechanism is document-scoped and less flexible than the broader referencing capabilities of XSD key/keyref constraints.
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE catalog [

    <!ELEMENT catalog (product*, order*)>
    <!ELEMENT product (name, description?)>
    <!ELEMENT order   (lineItem+)>
    <!ELEMENT lineItem EMPTY>
    <!ELEMENT name        (#PCDATA)>
    <!ELEMENT description (#PCDATA)>

    <!-- ID attribute: must be unique across the document -->
    <!ATTLIST product
        id       ID                    #REQUIRED
        status   (active|discontinued) "active"
        sku      NMTOKEN               #IMPLIED
    >

    <!-- IDREF links back to a product's id -->
    <!ATTLIST lineItem
        productRef IDREF  #REQUIRED
        quantity   CDATA  #REQUIRED
        unit       (each|kg|litre) "each"
    >

    <!-- FIXED attribute: always has this value if present -->
    <!ATTLIST catalog
        xmlns    CDATA   #FIXED "http://example.com/catalog"
        version  CDATA   #FIXED "1.0"
    >

]>
<catalog>
    <product id="p001" sku="WH-100">
        <name>Wireless Headphones</name>
    </product>
    <product id="p002" status="discontinued" sku="SP-200">
        <name>Bluetooth Speaker</name>
        <description>Portable speaker, waterproof.</description>
    </product>

    <order>
        <lineItem productRef="p001" quantity="2" unit="each"/>
        <lineItem productRef="p002" quantity="1"/>
    </order>
</catalog>