O'Reilly logo

Java Cookbook by Ian F. Darwin

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

Generating Your Own XML with DOM

Problem

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

Solution

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

Discussion

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 . DocWrite.java
$ java DocWrite
<?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 21-8.

Example 21-8. DocWrite.java

import java.io.*; 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); ...

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