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:

  1. #PCDATA must come first: The declaration must always begin with #PCDATA (Parsed Character Data).
  2. Use the choice separator (|): Individual child element names must be separated from #PCDATA and each other using the vertical bar (|). Sequences using commas (,) are not permitted in mixed content declarations.
  3. 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: