Writing XML Documents with JDOM

Once you’ve created a document, you’re likely to want to
serialize it to a network socket, a file, a string, or some
other stream. JDOM’s
org.jdom.output.XMLOutputter class
does this in a standard way. You can create an
XMLOutputter object
with a no-args constructor
and then write a document onto an
OutputStream with its
output() method. For example, this
code fragment writes the Document object
named doc
onto System.out.

Besides streams you can also output a document onto a
java.io.Writer. However, it’s
recommended that you use an OutputStream
because it’s generally not possible to determine the underlying
encoding of a Writer and set the
encoding declaration accordingly.

Besides documents, XMLOutputter
can write elements, attributes, CDATA
sections, and all the other JDOM node classes. For example, this
code fragment writes an empty element named
Greeting
onto System.out:

This may occasionally be useful; but if you write anything
other than a single Document
or Element onto a
stream, the result probably won’t be a well-formed XML
document.

Finally, instead of writing onto a stream or writer, you can
use the outputString() methods to
store an XML document or node in a
String. This is often useful when
passing XML data through non-XML aware systems. For example, this
code fragment stores an empty element named
Greeting in the String variable
named hello:

This isn’t especially pretty. There are a couple of ways to
clean it up. First off you can recognize that white space is
significant in XML and by default JDOM faithfully reproduces
it. Thus if you want the output to be indented, you could
add strings containing line breaks and extra space in the
right place.
However, if you happen to know that white space is not
significant in the particular XML vocabulary the program
writes, then you can ask the XMLOutputter
to format the document for you. For example,
this XMLOutputter inserts the default
line ending after elements and indents elements by two spaces
per each layer of the hierarchy:

For another example, let’s revisit
FlatXMLBudget,
Example 4.2 from
Chapter 4. Recall that its purpose was
to read a tab-delimited file containing financial data and
convert it into XML. The method that actually generated the XML
was
convert(), and it did this by writing
strings onto an OutputStream like so:

The disadvantage to this approach is that even though the
input is streamed the output is not. The entire document
is built and stored in memory before the first byte of output
is written.
This can be a problem in memory limited devices or with large
documents.