XML technologies / XML / XML in a Nutshell / Programming models / Common XML processing models
(Excerpt from “XML in a Nutshell” by Elliotte Rusty Harold & W. Scott Means)
Developers can process XML-structured and marked-up text in different ways: as plain text, an event sequence, a tree, or a serialization of another structure. Tools for all these approaches are widely available.
Text-based XML processing
XML documents are fundamentally text: both content and markup are represented textually. Text editors therefore help analyze, create and modify documents. This lets developers work directly with XML and turn to dedicated XML tools only when necessary.
Easy parsing was an original XML design goal. For simple documents without defaults or validation, standard tools such as regular expressions and tokenizers can parse tags, attributes and text. Complexity rises quickly with additional features. Unless an application fully controls incoming content, it is almost always preferable to use one of the many high-quality XML parsers freely available for most programming languages.
Text tools nevertheless remain important parts of XML toolkits. Many developers create and modify XML with editors such as vi, Emacs, NotePad, WordPad, BBEdit or UltraEdit. Regular expressions are used in environments including sed, grep, Perl and Python for operations such as search and replace. They also optimize XML before parsing or further processing with XSLT. Standards increasingly exploit regular-expression matching after parsing. The W3C XML Schema Recommendation, for example, includes regular-expression matching as a validation mechanism for data types.
Text processing can combine with other XML approaches. Parsing and subsequent serialization may not yield the desired result. XSLT, for example, resolves entity references. To preserve the entities, replace them with unique placeholders in the source, then restore the references in the result. Regular expressions make this easy.
Warning: Select text tools carefully because XML depends on Unicode. Many environments have added Unicode support, but not all. Before editing parser output, check the tool’s Unicode support; for original XML, it must support the document’s character set. Most modern languages, including Java, C#, Perl 5.6 and Python 2.2, and tools support Unicode. Problems arise mainly in C and C++, where you must consider whether to use wchar or char and understand what a wchar actually means on a given platform.
Event-driven XML processing
A parser reads from the document’s beginning to its end, perhaps pausing to consult external sources for a DTD or external entity. It learns about the document as it goes. Once parsing succeeds completely, tree-based technologies such as DOM combine these incremental events into one monolithic representation.
Event-based parsers instead report processing events to the client as they occur, including reading start-tags, element content and start-tags. Consider this example document.
<name>
<vorname>Keith</vorname>
<nachname>Johnson</nachname>
</name>Code example: Simple XML document
An event-driven parser would report events such as:
startElement:name startElement:vorname content:Keith endElement:vorname startElement:nachname content:Johnson endElement:nachname endElement:name
The event list and structure become more complex when the source adds namespaces, attributes, whitespace between elements, comments, processing instructions or entities. The basic mechanism remains simple and generally efficient.
Event-driven applications are usually more complex than tree-based ones. They generally require a state machine tracking context and interpreting event information. Because events occur while reading, partial results must be discardable if a fatal error occurs later. Accessing widely scattered document data also requires more effort than with a parsed tree.
Event APIs offer speed and efficiency. Streaming lets processing start immediately after the beginning is read, before reaching the end. For example, a stock-trading program receiving many purchase orders can execute the first before the parser reads the second, the second before the third, and so on. For a document with many orders this saves critical seconds on the earliest trades.
Size matters even more. XML may contain gigabytes of data; event APIs need not hold it all in memory. They process manageable chunks and reuse memory. In practice, documents exceeding a few hundred megabytes cannot be processed with a tree API even on large servers with gigabytes of RAM. Embedded environments such as phones make event APIs essential because of memory limits.
Event parsers naturally suit tasks such as filtering. Filters process and modify events before passing them onward, efficiently performing many transformations. Chained filters form pipelines passing one process’s results directly to another. Events are also ideal for feeding XML information into internal application structures. Even parsers returning complete trees usually build them from events; the next section describes these.
Note: The Simple API for XML (SAX) is the most widely used event-driven API. SAX 2.0.1 is the current version. Expat, a widely used parser written in C, also uses an event-driven API.
Tree-based XML processing
XML documents are easily described as trees because of well-formedness requirements. Elements are inherently hierarchical, containing other elements, text, comments and so on.
XML documents have many different tree models. XPath is used in XSLT transformations and has somewhat different constraints from the DOM API. Still other assumptions apply to the XML Information Set (Infoset), another W3C project. XML Schema defines a Post-Schema Validation Infoset (PSVI) derived from XML schema. It contains more information than any other tree model.
Developers manipulating documents in programs generally use APIs exposing an object-model representation. Tree APIs normally provide the complete model after successful parsing. Applications must track parsing context manually or handle partially processed documents after errors, since tree parsers generally handle errors themselves. Instead of following events, they navigate the tree to find the desired parts.
Trees offer important advantages. The whole document and the full context of every part are always available. Balanced portions can easily be changed or moved. APIs supporting XPath let developers locate content and make content-dependent decisions anywhere. DOM Level 3 formally supports XPath, while various implementations already provide proprietary support.
Trees also have drawbacks. They commonly use three to ten times the original file’s memory. Navigation gives developers more options but may demand further processing after parsing; trees impose less discipline than event processing. These issues complicate scaling and exchanging tree-based applications. Nevertheless, trees may suit small documents or small document sets.
Note: The Document Object Model (DOM) is the most widely used tree API. JDOM, DOM4J and XOM are Java-only alternatives. XOM is an object model promoted by coauthor Elliotte Rusty Harold.
Pull-based XML processing
The newest contender is the pull processing model. Microsoft’s .NET class XMLReader is a widely used pull processor. Pull most resembles events in that content becomes available incrementally during parsing.
Unlike events, however, clients request content according to their needs. For example, a pull client might use the following code to parse the document in Simple XML document:
reader.ReadStartElement("name") reader.ReadStartElement("given") givenName = reader.ReadString( ) reader.ReadEndElement( ) reader.ReadStartElement("family") familyName = reader.ReadString( ) reader.ReadEndElement( ) reader.ReadEndElement( )
The client requests the XML content it wants from the pull parser. In practice, client code is easier to read and understand than equivalent event code. Fewer stacks and structures are needed to hold document information because the code itself can mirror recursive-descent parsing.
In Java, BEA, Sun and individual developers collaborated on the Streaming API for XML (StAX). StAX and other pull parsers share with SAX the streaming benefits—speed, concurrency and memory efficiency—but offer an API many developers find easier. SAX and other push parsers use the Observer pattern; StAX, XMLReader and other pull parsers use the Iterator pattern.
Transformations
Transformations provide another option. The Extensible Stylesheet Language Transformation (XSLT) is widely used to convert XML to HTML, XML and other presentation formats. Pre- or postprocessing transformations can simplify DOM or SAX applications. XSLT might preprocess XHTML documents for screen scraping, turning a complex XHTML document into a smaller, accessible application-specific XML format for a script to process.
Transformations work independently, in browsers or from the command line. Many XSLT implementations and other tools expose SAX or DOM interfaces, simplifying creation of transformation pipelines for document processing.
Hiding XML
Developers wanting XML’s cross-platform advantages without handling markup can use tools hiding XML structures. Web services such as REST and SOAP are steps in this direction. Direct file access remains possible, but toolkits let you avoid it.
Such applications generally add a layer over event or tree processing, exposing their own API to underlying information. In our view, XML data is usually already as clear and accessible as possible. Extra abstraction layers generally increase application complexity and rigidity.
Standards and extensions
SAX, DOM and other core specifications underpin XML processing. Implementations, especially of DTDs, sometimes depart from them. Some extensions have formal definitions. SVG, for example, defines DOM extensions for SVG work. Others are additions a programmer or vendor deemed necessary beyond the original specification. DOM levels and modules have led developers to claim DOM support while actually supporting only a particular subset or extension.
Porting standards creates further variants. SAX originated in Java, and its core project defines only a Java API. DOM describes its API in IDL, but implementations interpret it differently. SAX2 and DOM are generally portable, although details vary between environments.
Some environments also provide libraries independent of SAX and DOM. Perl and Python combine event and tree processing, letting applications work on subtrees rather than events or whole trees. These nonstandard approaches complicate switching environments but can be useful.
Combining models
Text, events, trees and transformations can be combined despite their differences. Most DOM parsers support SAX events; tools convert between SAX and DOM in both directions. Some tools consuming and producing events internally use trees, as many XSLT processors do, with an optimized internal model rather than DOM. XSLT processors also often accept SAX events or DOM trees as input and produce these models or text as output.
Programmers often start with DOM trees because they are initially easier to understand. If event-oriented problems arise, they can rewrite their code, a substantial task, or combine and coordinate event and tree processing.
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