Generating Your Own XML with DOM


You want to generate your own XML files or modify existing documents.


Use DOM or JDOM; parse or create the document, and call its write method.


Sun’s XmlDocument class has a write( ) method that can be called with either an OutputStream or a Writer. To use it, create an XML document object using the XmlDocument constructor. Create nodes, and append them into the tree. Then call the document’s write( ) method. For example, suppose you want to generate a poem in XML. Running the program and letting the XML appear on the standard output might look something like this:

$ jikes +E -d .
$ java DocWrite
<?xml version="1.0" encoding="UTF-8"?>

    <Line>Once, upon a midnight dreary</Line>
    <Line>While I pondered, weak and weary</Line>

The code for this is fairly short; see Example 21-8.

Example 21-8.

import*; import org.w3c.dom.*; import com.sun.xml.tree.*; /** Make up and write an XML document */ public class DocWrite { public static void main(String[] av) throws IOException { DocWrite dw = new DocWrite( ); XmlDocument doc = dw.makeDoc( ); doc.write(System.out); } /** Generate the XML document */ protected XmlDocument makeDoc( ) { try { XmlDocument doc = new XmlDocument( ); Node root = doc.createElement("Poem"); doc.appendChild(root); Node stanza = doc.createElement("Stanza"); root.appendChild(stanza); Node line = doc.createElement("Line"); stanza.appendChild(line); ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.