O'Reilly logo

Java and XML by Brett McLaughlin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

XML from Scratch

One item we have not yet addressed is the idea of building up an XML document from scratch; this is common when either no original document exists, or the original document is so complex that it is easier to rebuild it than to modify it. Building a new XML document is also valuable when the output of an application should be XML suitable for another application component to use (such as in a business-to-business application, discussed in Chapter 13). In these cases, we need to create XML documents rather than just modify existing ones. Fortunately, this is not a large change for our JDOM code. Because JDOM relies on SAX and DOM (or any other implementation) only in the building of the initial JDOM Document object, all other interaction with the API is uncoupled from that building process; if a new XML document needs to be created, the Builder classes are simply not used. The JDOM Document is created with a new root element, added to and manipulated, and then output with a Formatter class. Seems a little simple, right? Example 12.4 shows the saveConfiguration( ) method we have been looking at modified to create a new Document to output as our XML-RPC configuration file.

Example 12-4. Building XML from Scratch

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required