Java Reference
In-Depth Information
which doesn't actually indent but at least causes line breaks). Wrap the document in a
DomSource object, and the output stream in a StreamResult object. Pass the wrapped input
and output into the Transformer 's transform() method, and it will convert the in-memory
tree to text and write it to the given StreamResult .
For example, suppose you want to generate a poem in XML. Example 20-14 shows what
running the program and letting the XML appear on the standard output might look like.
Example 20-14. DocWrite.java
$ java xml . DocWriteDOM
Writing the tree now ...
<? xml version = "1.0" encoding = "UTF-8" ?>
< Poem >
< Stanza >
< Line > Once , upon a midnight dreary </ Line >
< Line > While I pondered , weak and weary </ Line >
</ Stanza >
</ Poem >
$
The code for this is fairly short; see Example 20-15 for the code using DOM. Code for using
JDOM is similar but used JDOM's own classes; see DocWriteJDOM.java in the javasrc pro-
ject.
Example 20-15. DocWriteDOM.java
public
public class
class DocWriteDOM
DocWriteDOM {
public
public static
static void
void main ( String [] av ) throws
throws Exception {
DocWriteDOM dw = new
new DocWriteDOM ();
Document doc = dw . makeDoc ();
System . out . println ( "Writing the tree now..." );
Transformer tx = TransformerFactory . newInstance (). newTransformer ();
tx . setOutputProperty ( OutputKeys . INDENT , "yes" );
tx . transform ( new
new DOMSource ( doc ), new
new StreamResult ( System . out ));
}
/** Generate the XML document */
protected
protected Document makeDoc () {
try
try {
DocumentBuilderFactory fact = DocumentBuilderFactory . newInstance ();
DocumentBuilder parser = fact . newDocumentBuilder ();
Document doc = parser . newDocument ();
Search WWH ::




Custom Search