Understanding Mixed Content Elements in XML and XSD
In XML, a mixed content element is an element that can contain both
character data (text) and other child elements simultaneously. This
article provides a clear overview of what mixed content elements are,
illustrates their practical use in markup scenarios, and explains the
step-by-step method for declaring them inside an XML Schema Definition
(XSD) using the mixed="true" attribute.
What is a Mixed Content Element?
A mixed content element allows character data to appear interspersed with child tags within the same parent element. This pattern is common in document-oriented XML applications, such as formatting rich text, where specific words or phrases inside a sentence require tags for styling or semantic meaning.
Example of Mixed Content in XML
<letter>
Dear <name>John Doe</name>,
Your order <orderId>98765</orderId> has been processed.
</letter>In this example, <letter> is a mixed content
element because it contains plain text ("Dear ",
", Your order ", " has been processed.")
alongside child elements (<name> and
<orderId>).
How to Declare Mixed Content in XML Schema (XSD)
In an XML Schema, an element with mixed content must be declared as a
complex type. To enable mixed content, you set the mixed
attribute of the xs:complexType element to
"true".
XSD Declaration Syntax
<xs:element name="letter">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="orderId" type="xs:positiveInteger"/>
</xs:sequence>
</xs:complexType>
</xs:element>Key Rules for XSD Mixed Content
- Default Value: The
mixedattribute defaults to"false". If omitted, the element cannot contain raw text alongside child elements. - Structural Validation: Setting
mixed="true"does not disable validation for the child elements. The schema still enforces rules specified inside<xs:sequence>,<xs:choice>, or<xs:all>. - Text Placement: While the schema controls the occurrence and order of child elements, it does not restrict where the text appears relative to those child elements. Text can be placed before, between, or after any child tag.