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; ...
Get Java and XML now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.