XML technologies / XML / XML in a Nutshell / Programming models / General guidance on XML processing
(Excerpt from “XML in a Nutshell” by Elliotte Rusty Harold & W. Scott Means)
When developing a new XML application, as with any technology, most design goals can be implemented in several ways, and some pitfalls deserve early attention. Knowing what the new features are intended for helps the application remain compatible not just with known target systems but also with XML-processing tools that may not yet exist.
What You Get Is Not What You Saw
The XML specification sometimes gives an XML parser some latitude in interpreting a document’s content, provided its meaning remains intact. This chiefly concerns comments, which may be omitted, and references to entities, which the parser may replace silently without warning the client application. A document should be reconstructible with the same logical structure, but byte-for-byte identity is generally not intended.
Note: XML Canonicalization defines a more consistent XML structure and a process for producing it, making reconstruction from a document’s logical model much more predictable.
Authors of simple XML tools that neither store nor modify data may not find these restrictions troublesome. Exact reconstruction from in-memory structures is critical, however, for XML editors and content-management systems. Though no parser must expose comments, ignorable whitespace or entity references, many can do so or can be configured accordingly.
To ensure a parser outputs documents as you require rather than merely meeting XML’s minimum requirements, read its documentation and configure or select it accordingly.
To read or not to read the DTD?
DTDs come in internal and external forms, sometimes both together. XML requires every parser to read the internal DTD subset. Validation requires reading the external subset, if present; without validation this is optional. Reading it takes extra time, especially for large DTDs or remote hosts, so you might skip it when not validating. Most parsers offer options controlling resolution of external DTD subsets and other external entities. Were validation the DTD’s only purpose, the choice would be simple. Unfortunately, DTDs also add important properties to the document’s Infoset. These include:
Entity definitions
Default attribute values
Whether boundary whitespace may be ignored
A document with a non-well-formed DTD is itself non-well-formed, so the DTD may even determine whether it is readable. A parser’s report can therefore depend crucially on reading the external subset. For maximum interoperability, provide documents without external DTD subsets: behavior then becomes predictable and reproducible regardless of configuration. Conversely, consumers wanting to receive exactly what the sender intended should try to read any referenced external subset. Be conservative in what you send, avoiding external subsets, and liberal in what you receive, reading them when present.
Whitespace
Parser whitespace handling is among the most misunderstood aspects of XML processing. Remember four basic rules:
All whitespace in element content is always reported.
Whitespace in attribute values is normalized.
Whitespace in the prolog, epilog and tags outside attributes is not reported.
All unescaped line breaks—carriage returns, line feeds, carriage-return/line-feed pairs and, in XML 1.1, NEL and Unicode line separators—are converted to line feeds.
Consider this code example:
<!DOCTYPE person SYSTEM "person.dtd ">
<person quelle="Alan Turing: Die Enigma,
Andrew Hodges, 1983">
<name>
<vorname>Alan</vorname>
<nachname>Turing</nachname>
</name>
<beruf id="p1"
wert="Informatiker "
quelle="" />
<beruf id="p2"
wert="Mathematiker"/>
<beruf id="p3"
wert="Kryptograph"/>
</person>Reading this document, a parser reports all element-content whitespace to the client. This includes boundary whitespace between start-tags <name> and <first> and end-tags </nachname> and </name>. If the DTD says the element name cannot have mixed content, this whitespace is considered element-content whitespace, also called ignorable whitespace. The parser still reports it. Whether ignorable or not, the receiving application may ignore boundary whitespace as document-formatting decoration. The parser always reports it all.
Line breaks and other whitespace in the prolog and epilog are not reported by the parser. Nor does it report line breaks and whitespace within tags, such as between attributes id and wert of the elements beruf. Your program must not depend on such information.
The parser normalizes attribute whitespace. At minimum, line breaks such as those in the attributes quelle become spaces. That is all if the DTD declares type CDATA, the attribute is undeclared, or the DTD is unread or absent. For any other type, such as ID or NMTOKENS, or an enumeration, the parser trims leading and trailing whitespace and collapses remaining sequences to single spaces. Only literal whitespace is normalized. Spaces, tabs and carriage returns embedded in character or entity references become replacement text and are then preserved, unlike literal whitespace.
Entity references
XML instance documents have three kinds of references, plus two others in the DTD which we can ignore for now:
Numeric character references such as
 and The five predefined entity references
&,>,",'and<General entity references defined in the DTD, such as
&kapitel1;and
The first two kinds are straightforward: the parser always resolves them without telling you. As a parser client, ignore them and the right thing happens. Replacement text is reported like ordinary text, without even noting that references occurred. Rarely, a special parser property may expose such details, but you will almost never want it. It makes sense only when writing an XML editor trying to round-trip the document’s source form.
The third case is trickier. References may point to remote files you do not always want to access for performance, availability or security reasons. Even internal entities may be declared in a remote external subset. Parser defaults vary; most parsers and APIs let you control loading, but not all. XOM always resolves external entities, whereas Mozilla’s XML parser never does. A parser that does not resolve one should notify its client, for example by calling the SAX skippedEntity( ) method or, in DOM inserting an EntityReference object into the tree. The application’s response depends on context. Sometimes this is fatal; sometimes it can be worked around or ignored. Account for this possibility whenever the parser is not configured to resolve all external entities.
Note: Recently some parser vendors have addressed so-called Billion Laughs attacks. In brief, they define entity references whose size doubles repeatedly. This matters especially in the internal DTD subset, where entities must be resolved:
<!ENTITY ha1 "Ha! ">
<!ENTITY ha2 "&ha1; &ha1;">
<!ENTITY ha3 "&ha2; &ha2;">
<!ENTITY ha4 "&ha3; &ha3;">
<!ENTITY ha5 "&ha4; &ha4;">
<!ENTITY ha6 "&ha5; &ha5;">
...
<!ENTITY ha31 "&ha30; &ha30;">
<!ENTITY ha32 "&ha31; &ha31;">
...
<root>&ha32;</root>CDATA sections
The golden rule for CDATA sections is: ignore them! When writing XML-processing code, assume there are no CDATA sections and everything will work properly. The content of CDATA sections is plain text, reported like any other text whether enclosed in a CDATA section, escaped by a character reference or written literally when no escaping is needed. These two elements beispiel are therefore identical as far as your code needs to know or care:
<beispiel><![CDATA[<?xml version="1.0"?>
<wurzel>
Hallo!
</Wurzel>]]></beispiel>
<beispiel>&lt;?xml version="1.0"?>
&lt;wurzel>
Hallo!
&lt;/wurzel></beispiel>Do not write programs or documents that depend on the distinction. Parsers rarely, and never reliably, expose it. Furthermore, CDATA sections often disappear in processing pipelines. Their content survives but is represented differently, for example with numeric references for non-serializable characters. CDATA sections are merely a small convenience for human authors. Do not treat them as markup.
This also means you should not use CDATA sections to embed an XML or HTML document in another. XML was not designed for such nesting. Namespaces are the proper solution, identifying which markup is which; do not use one document as an envelope for another. Nor should you use CDATA sections to escape non-well-formed markup common in HTML systems. Clean up the HTML with a suitable tool before embedding it in XML.
Comments
Although HTML has long used comments for server-side includes (SSI) and to hide JavaScript programs and Cascading Style Sheets, using comments for anything but human-readable annotations is generally unwise. XML parsers may, and often do, ignore comments entirely, preventing them from reaching applications. Transformations generally ignore them too.
Processing instructions
XML parsers must give clients access to XML processing instructions. These let document authors communicate with XML-aware applications without interfering with document content. DTD and schema validation ignore them, so they may occur anywhere in the document structure without changing its DTD or schema. Their most common use references stylesheets, as in this fragment:
<?xml-stylesheet type="text/css" href="test.css"?> An XML-aware application such as Internet Explorer 6.0 would read this as the author’s suggestion to use stylesheet test.css to display the content. Such instructions may also reference XSLT stylesheets or formats not yet known. The client must know how to process them. Applications that do not understand the processing instruction can still read the document and understand its content by ignoring the instruction.
The furniture example introduced in Some annotated sample documents in the XML reference (see “Figure: buecherregal.xml”) contains instructions for a hypothetical application. In the XML document buecherregal.xml an instruction tells the example’s processor to compare the document’s parts list with the parts actually required for the furniture item.
<teileliste>
<teilename id="A" count="1">Rückwand</teilename>
<teilename id="B" count="2">Seitenwand</teilename>
<teilename id="C" count="1">Front</teilename>
<teilename id="D" count="4">Brett</teilename>
<teilename id="E" count="8">Versteckte Halterung</teilename>
<teilename id="F" count="8">Halterungsschrauben</teilename>
<teilename id="G" count="22">7/16" Muttern</teilename>
<teilename id="H" count="16">Dübel</teilename>
</teileliste>
<?MoebelPruefer teileliste_pruefen?>If the application does not recognize the instruction type or target, the instruction is considered meaningless.
XML also allows a link between the processing-instruction target, the XML name immediately following <?, and a notation. This is not really necessary and is rarely used.
Notations
XML notation syntax lets authors identify an external unparsed entity’s type within XML. If an application needs external data not representable in XML, introduce a notation name and use it to define external unparsed entities. For example, a document could contain Java source and a link to compiled bytecode as an external unparsed entity.
Notations are metadata, labels describing document information. Declare them in the DTD as described in External unparsed entities and notations. One use is an attribute specifying type NOTATION. A document with scripts for different environments could introduce notations and an attribute specifying the notation. That attribute then describes more precisely the kind of script within an element:
<!NOTATION DOS PUBLIC "-//MS/DOS Batch File/">
<!NOTATION BASH PUBLIC "-//UNIX/BASH Shell Script/">
<!ELEMENT batch-code (#PCDATA)*>
<!ATTLIST batch-code lang NOTATION (DOS | BASH)>
. . .
<batch-code lang="DOS">echo Hallo Welt!</batch-code>Applications familiar with the PUBLIC identifier can interpret the element correctly according to the type specified by the attribute lang. Notations also support SYSTEM identifiers, and applications may handle both identifier types correctly.
Another use categorizes processing instructions. For example, the instruction MoebelPruefer just shown could be declared as a notation in the DTD as follows:
<!NOTATION MoebelPruefer SYSTEM "http://namespaces.example.com/moebel"> The furniture-processing program could then recognize that the instruction is intended for it rather than another program using the same instruction name.
Unparsed entities
Unparsed entities combine attributes and notation declarations to reference content requiring application-specific processing that is not yet specified. Applications rarely use this feature.
Copyright © 2005 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XML in a Nutshell” 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