XML technologies / XML / Python & XML / XML basics / Document type definitions
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
As mentioned earlier, document type definitions, or DTDs, are the document type mechanism specified by the XML 1.0 Recommendation. Despite alternatives, DTDs remain among the most common ways to specify a document type. This section explains the syntax of the declarations that may appear in the document type declaration; all may occur in either external or internal subsets.
Entity declarations
Entities are data sources used to assemble a larger construct. Most, called general entities, construct documents, but some, known as parameter entities, construct the document type itself. Both are defined with an entity declaration in the document type definition. Each kind of entity occupies a separate namespace; a general entity named myEntity and a parameter entity of the same name may coexist without a name collision.
Entities may be declared more than once; the first definition of a name takes precedence. This lets the internal subset override the external subset’s definition. With parameter entities, this mechanism can extend DTDs. Extending document types usually works best when the DTD being extended was carefully designed for this purpose. The DocBook DTD for technical documentation is an excellent example.
General entities may take many forms: parsed entities consisting of XML text, or unparsed entities, such as an image file stored as Portable Network Graphics (PNG). A parsed entity’s text may occur in its declaration or an external source. An unparsed entity’s body is always external. Most entities used with XML are parsed; unparsed constructs such as images are generally referenced by an absolute or relative URL rather than a named entity.
Parsed general entities define replacement text for a usually shorter name. Remember that XML text includes markup as well as character data, so replacement can add document structure, provided all structures within it are complete. During processing, a parser resolves entities to their replacement text and reevaluates the document after substitution. Creating a simple internal entity requires only a symbol and its replacement text:
<!ENTITY sandwich "Krabben-Pastetchen"> Every reference to &sandwich; anywhere in your document is replaced by the text “Krabben-Pastetchen”. For example:
Ich habe Hunger auf ein &sandwich;.
This sentence is displayed as follows:
Ich habe Hunger auf ein Krabben-Pastetchen.
External entities are defined by an entity declaration specifying the URL of an external resource containing the replacement text:
<!ENTITY legal SYSTEM "http://www.example.com/legal.xml"> All references to &legal; in a document produce:
<legal>Copyright 2001, Example GmbH</legal>. External entities replace symbols with the corresponding text, just like internal entities. This is sometimes necessary when text contains characters otherwise treated as markup, such as the special characters < , > and & in your XML code. Entities may also hold boilerplate information normally maintained elsewhere and made available to the document.
Parameter entities differ in use and applicability. They construct document type definitions, not documents themselves. XML syntax prohibits references to parameter entities from document content, allowing them only in internal and external DTD subsets. There are no unparsed parameter entities, though non-validating parsers may ignore them. Validating parsers must parse every referenced parameter entity.
A parameter entity declaration resembles a general entity declaration with a few additional characters:
<!ENTITY % node-decls SYSTEM "node-decls.dtd"> It contains something absent from general entity declarations: the percent sign (%) between the keyword ENTITY and the entity name, with required whitespace on both sides. This parameter entity would be used as follows:
%node-decls; Notice that a parameter entity reference starts its name with a percent sign rather than an ampersand (&). This is necessary because the two sets of names may overlap.
Entity replacement works much like general entities: replacement text substitutes for the reference, after which document-type interpretation continues with the modified text.
Parameter entities are most useful with modularized document types providing carefully designed extension mechanisms. A large DTD, such as the industry-standard DocBook DTD for software documentation, can be customized by creating a new document type that defines a few parameter entities and then reads the standard DocBook definition. Because the entity declarations defined in the customization layer override DocBook’s declarations, this mechanism can extend or restrict the document type for a project’s specific purposes.
Element type declarations
Element type declarations constrain element content. They specify which element types may be children and how those children may be arranged. They can look like this:
<!ELEMENT br EMPTY>
<!ELEMENT generic ANY>
<!ELEMENT name (address+)>
<!ELEMENT para (#PCDATA | list | picture)*>We can split the declaration into syntactic components, each with a particular purpose:
<!ELEMENT name content-model> The text <!ELEMENT tells the parser this is an element type declaration. name names the element type so other parts of the document type definition can reference it. content-model specifies what content the element may contain: character data, other elements or both. No element type may be declared more than once.
Interestingly, there is no place to declare attributes. Though associated with element types, attributes are defined separately by attribute declarations, described later in Attribute declarations.
Content models
A content model describes the allowed child elements of a declared element type, their permitted order and combinations, and whether arbitrary character data is allowed.
All element content models fall into two categories:
Element content
Content consisting only of elements: for example, an address element requiring child elements but no character data. The specification defines content particles consisting of names, choice lists of content particles or sequence lists of content particles.
Mixed content
This content may include character data. It is the most common arrangement in text documents:
<news title="XML aus dem Weltall">
Dieser Artikel beschreibt XML-Übertragungen aus dem Weltall.
<h1>Kein Meteor</h1>
<para>Entgegen früherer Berichte ist das XML, das aus dem Weltall gelandet ist, kein Meteor.</para>
</news>This example places both elements and character data in the
newselement. Elements with mixed content need not allow other elements. Indeed, an element type permitting only character data may remain entirely empty; there is no way to require actual characters in the character data.
Let us revisit the example element declarations:
<!ELEMENT br EMPTY> These element type declarations are simple. The first content model, EMPTY, describes an empty br element such as those found in XHTML. It allows no child elements or character data, but may still contain non-content constructs such as comments and processing instructions. An element type declared EMPTY is considered a degenerate special case of element content.
<!ELEMENT generic ANY> Next is an element named generic, allowing any element type defined in the document type, but not undefined types. It also allows character data, so the content model of ANY is mixed.
<!ELEMENT name (address+)> The third example is simple but quite different. Instead of a name such as ANY or EMPTY, something resembling a regular expression describes the model. Here an element name requires one or more address elements. This probably most common model allows more detail. Models can reach varying levels of complexity, but always aim to define the content permitted or expected inside the element.
The model uses parentheses and commas to indicate a sequence. A vertical bar (| ) indicates a choice. For example:
<!ELEMENT name (first, last)> This element type requires a child element first followed by a child element last and nothing else. To allow either first or last, use a vertical bar:
<!ELEMENT name (first | last)> These expressions can also be nested:
<!ELEMENT order (sku, quantity, (account | name), price)> The above element order requires a child sku followed by an element quantity, then either an element account or an element name, and finally an element price.
The operators +, * and ? may also be appended to content expressions to specify occurrence counts, repeatability or optionality. Without modifiers, the element must occur exactly once at that position. The list below explains the operators:
+ Content must occur one or more times.
* Content may occur zero or more times.
? Content may occur zero or one time.
For example, to obtain an element order with exactly one account followed by one or more sku and one or more price elements, and exactly one optional ship element, you could use this element type:
<!ELEMENT order (account, sku+, price+, ship?)> To combine character data and elements, use the oder operator and define mixed content as follows:
<!ELEMENT paragraph (#PCDATA | list | picture)*> This element type, named paragraph, permits repeated sequences of character data, indicated by the asterisk, list elements or picture elements within paragraph elements. #PCDATA can only be combined with elements using the oder operator in a group with a * modifier, and may occur only in the outermost parenthesized group of a content model.
Attribute declarations
As explained earlier, attributes specify name/value pairs as element properties. They occur only in start-tags and empty-element tags. An attribute-list declaration belongs to the DTD used to validate an XML document. For example:
<!ATTLIST news
title CDATA #REQUIRED
author CDATA #IMPLIED> This attribute-list declaration says every news element requires an attribute title containing character data and may optionally have an attribute author also containing character data.
Attribute data types
The specification distinguishes three attribute types: string, token and enumeration. In the preceding attribute-list example, an element news required an attribute title of string type CDATA.
There are several tokenized attribute types:
ID
A unique identifier for this element. It must be a name unique within the current document.
IDREF
Must match an
IDsomewhere in the XML document.
IDREFS
A whitespace-separated list of one or more names, each matching an
IDin the document.
ENTITY
Matches the name of an unparsed entity declared in the document.
ENTITIES
A whitespace-separated list of one or more entity names.
NMTOKEN
This rarely used type matches a
NMTOKENproduction as defined in the XML Recommendation. Consult that Recommendation for more information.
NMTOKENS
A whitespace-separated list of one or more
NMTOKENvalues. This is the least used attribute type.
The remaining attribute types, enumerations, are defined in the attribute list itself. They take a name from a defined list in an attribute declaration. Each distinct set of names forms a type of its own, without its own name. For example:
<!ATTLIST schiff typ (schaluppe | fregatte | schlauchboot) #IMPLIED> This declaration defines a type accepting one of the values schaluppe, fregatte or schlauchboot but no other value. The element <schiff typ="yacht"/> would cause a validation error.
Attribute values and constraints
An attribute declaration lets a document type define a default value for an absent attribute. It can also specify whether the attribute may be omitted. Consider a more interesting declaration:
<!ATTLIST kapitel
beschreibung CDATA #IMPLIED
autor CDATA #REQUIRED
email CDATA "info@example.com"
version CDATA #FIXED "1.0"
typ (normal|referenz|anhang) "normal"> The attribute beschreibung must be a string (CDATA) if specified, but is not required and has no default because it is declared #IMPLIED. Most HTML attributes are declared this way. The constraint #REQUIRED means the attribute autor must be present. As a string, it may be empty. If a string value is declared instead of #IMPLIED or #REQUIRED, as for the attribute email in our example, it becomes the default used when no value is specified in the document.
The constraint #FIXED can only accompany a default value, as seen for attribute version. The document may include the attribute, but its value must exactly match the default, though encoded using a different combination of characters, entity references and character references. A different value causes a parser error.
The attribute typ exemplifies an enumeration type like the earlier example. Defaults and constraints work as for other types, with one extra constraint: any specified value must be a name in the enumeration.
ID attributes have special behavior. Let us create an attribute for the element news defined earlier:
<!ATTLIST news
newsID ID #REQUIRED> In this attribute list, elements news must have an attribute newsID. Allowed values follow the rules of token type ID. In particular, the value of ID is a name, as defined in Names, and cannot appear more than once in an XML document as any attribute value of type ID. In other words, ID values must uniquely represent an element within a document. Here is a valid example:
<news newsID="id39">Text</news>
<news newsID="id40">Text</news> Because values of ID attributes must be unique within a document, this is invalid:
<news newsID="id39">Text</news>
<news newsID="id39">Text</news>Furthermore, no element may have more than one attribute ID defined. An element type may define more than one attribute of type ID, but each element may have at most one ID value. Consequently, some APIs can use the values of ID attributes to access specific document elements.
The most interesting aspect of ID attributes, however, is not the attributes themselves but the IDREF attribute type. A value may occur only once in a document with type ID, but any number of times as a value of an attribute IDREF or IDREFS. These types may only take values also appearing somewhere in the same document as the value of an attribute ID. An attribute IDREFS may take a whitespace-separated list of ID values, each of which must exist in the document. These values create internal links between elements that a validating parser must check. This is convenient when a simple tree does not adequately organize your data. Attributes ID, IDREF and IDREFS extend the data model to support connected directed graphs with typed edges.
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Python & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de