How to Define Mixed Content in an XML DTD
Mixed content in XML refers to element types that can contain character data (text) interspersed with child elements. In a Document Type Definition (DTD), defining mixed content allows elements to hold unstructured text alongside markup formatting, such as bold text or hyperlinks within a paragraph. This article explains the syntax rules, constraints, and standard implementation for declaring mixed content models in an XML DTD.
Syntax Rules for Mixed Content
To declare an element with mixed content, the
<!ELEMENT> declaration must follow a strict syntax
mandated by the XML specification:
#PCDATAmust come first: The declaration must always begin with#PCDATA(Parsed Character Data).- Use the choice separator (
|): Individual child element names must be separated from#PCDATAand each other using the vertical bar (|). Sequences using commas (,) are not permitted in mixed content declarations. - Repeat indicator (
*): The entire group must be enclosed in parentheses and immediately followed by an asterisk (*), indicating that character data and the specified child elements can appear in any order and any number of times.
The general syntax format is:
<!ELEMENT element-name (#PCDATA | child-element1 | child-element2 | ...)*>Basic Example
Consider a scenario where a <description> element
contains regular text along with formatting tags like
<emphasis> and <code>.
The DTD declaration is defined as follows:
<!ELEMENT description (#PCDATA | emphasis | code)*>
<!ELEMENT emphasis (#PCDATA)>
<!ELEMENT code (#PCDATA)>A valid XML instance matching this DTD would look like:
<description>
This is an <code>XML</code> example showing <emphasis>mixed content</emphasis> in action.
</description>Text-Only vs. Mixed Content
If an element contains only character data without any child tags, it is a simplified form of mixed content defined without the choice operator or asterisk:
<!ELEMENT title (#PCDATA)>Once additional child elements are introduced, the declaration must
expand into the full (#PCDATA | element)* structure.
DTD Limitations with Mixed Content
When using DTDs, mixed content models have specific limitations:
- No ordering control: You cannot enforce the order in which child elements appear relative to the text or to each other.
- No occurrence control: You cannot require that a
specific child element appears at least once (
+) or exactly once; the asterisk (*) is mandatory for the entire group. - No specific positioning: You cannot specify that an element must appear only at the beginning or the end of the text.