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); line.appendChild(doc.createTextNode("Once, upon a midnight dreary")); line = doc.createElement("Line"); stanza.appendChild(line); line.appendChild(doc.createTextNode("While I pondered, weak and weary")); return doc; } catch (Exception ex) { System.err.println("+============================+"); System.err.println("| XML Error |"); System.err.println("+============================+"); System.err.println(ex.getClass( )); System.err.println(ex.getMessage( )); System.err.println("+============================+"); return null; } } }
A more complete program, of course, would create an output file and have better error reporting. It would also have more lines of the poem than I can remember.
Sun’s
XmlDocument
class is not a committed part of the
standard, which is why the code imports
com.sun.xml.tree.*
. However, other vendors’ APIs
will likely have similar functionality. In Version 2 of the XML DOM
API, you can use the new XMLReaderFactory.createXMLReader( )
, which takes the name of the parser as
a string argument, which can in turn be loaded from a properties file
(see Section 7.8). This avoids having the parser
class
name compiled into your application.
18.117.230.81