XML technologies / XML / XML in a Nutshell / Programming models / Generating XML documents
(Excerpt from "XML in a Nutshell" by Elliotte Rusty Harold & W. Scott Means)
An often overlooked area of XML development is generating documents for other applications to use. Although XML documents can be processed in various ways, relatively few techniques are currently used to create new ones.
One of the simplest and most common approaches uses the development environment’s string or file processing capabilities to build an XML document directly. It is easy to understand, efficient, and immediately available to any programmer. This Java statement writes a simple XML document to a file output stream:
FileWriter out = new FileWriter("nachricht.xml");
out.write("<nachricht>Hallo Welt!</nachricht>");It is easy to see how to implement this in any other programming language. For example, the following C++ statement produces the desired result:
ofstream fout;
fout.open("nachricht.xml", ios::app);
fout << "<nachricht>Hallo Welt!</nachricht>";This is a perfectly valid approach worth considering if the XML document is not too complex and its structure does not change substantially during the application’s lifetime. The drawback of this approach is that it is much easier to generate malformed or invalid documents, since their structure is not validated or verified during generation. If you use this technique, ensure that your code and incoming data produce well-formed XML.
Note: If all this data validation seems messy, take a look at Genx. It is a C library written by Tim Bray, one of the authors of the XML specification, that generates Canonical XML.
Another common approach uses a tree-based API such as the DOM to build an XML document tree dynamically. Its advantage is that the library enforces well-formedness constraints and, with DOM Level 3, can be configured to enforce validity constraints as well.
The library-based approach is often more complex and less efficient than simple string processing. This code fragment creates the same document as above, this time using DOM:
DOMImplementation di;
...
di.createDocument(null, null, null);
Document doc;
Element elMsg = doc.createElement("nachricht");
elMsg.appendChild(doc.createTextNode("Hallo Welt!"));
doc.appendChild(elMsg);
LSSerializer lss;
. . .
FileWriter out = new FileWriter("nachricht.xml");
out.write(lss.writeToString(doc));This is somewhat more complex than the simple string-based approach shown above.
Copyright © 2005 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from the book "XML in a Nutshell" is subject to the same conditions as the printed edition: the work and all its parts are 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
back to top