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); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access