How XML Parsers Distinguish Ignorable Whitespace
XML parsers distinguish between ignorable whitespace and meaningful
text content by evaluating the XML specification rules, document type
definitions (DTDs) or XML schemas, and explicit scope attributes like
xml:space. While an XML processor inherently treats all
whitespace characters (spaces, tabs, line breaks) as significant text by
default, validation rules and contextual markup allow validating and
non-validating parsers to categorize formatting spaces as non-essential,
ignorable data.
1. The Default XML Standard Rule
According to the W3C XML recommendation, all characters within an element—including carriage returns, line feeds, tabs, and spaces—are technically character data. By default, a standard parser passes every single whitespace character to the downstream application as a text node unless explicitly instructed otherwise.
2. Schema and DTD Content Models
The primary mechanism for distinguishing ignorable whitespace is the element’s content model defined in a Document Type Definition (DTD) or XML Schema (XSD):
- Element-Only Content: If a DTD defines an element
as containing only child elements (e.g.,
<!ELEMENT book (title, author)>), any whitespace appearing between<book>and<title>or between child tags is recognized as formatting. A validating parser marks this as ignorable whitespace. - Mixed Content: If an element allows both text and
sub-elements (e.g.,
<!ELEMENT p (#PCDATA | b)*>), the parser cannot assume whitespace is merely formatting. All whitespace within this element is marked as meaningful character data. - Simple/PCDATA Content: Elements declared to hold
only text (e.g.,
<!ELEMENT title (#PCDATA)>) preserve all whitespace, such as spaces between words or leading/trailing indents, as meaningful content.
3. The xml:space
Attribute
Authors can override or enforce whitespace behavior directly in the
XML document using the standard xml:space attribute:
xml:space="preserve": Instructs the parser and consuming application to treat all whitespace within that element and its descendants as significant text, regardless of DTD/schema declarations.xml:space="default": Restores the application’s default whitespace handling mechanism.
4. How Parsers Expose the Difference
- SAX Parsers: Feature two separate callback methods.
Meaningful text is sent via the
characters()event, while ignorable formatting whitespace from element-only content models is routed to theignorableWhitespace()event. - DOM Parsers: Non-validating DOM parsers generate
separate
Textnodes for every block of whitespace. Validating DOM parsers with whitespace stripping enabled will discard whitespace-only nodes located within element-only containers before building the node tree.