Java Tutorial - Java Scipt : DOM Parser Test

Java Tutorial - Java Scipt :

DOM Parser Test

The DOM parser example is the template for the other parser tests. First, a new XMLdocument is created and written to the file system. Then, the sample code will parse back in the order.xml file. In the code, you’ll notice a hack using the XSL interfaces to dump a copy of the XML document to System.out. Other high-level XML tools provide output classes and pretty printers for writing out XML, so that we don’t need to
use this trick.

Here’s the source code for jdk14_dom_test.java:

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class jdk14_dom_test {
public static void main( String args[] ) {
try {
//--- Create a new DOM document. ---
DocumentBuilder oBuilder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document oDocument =
oBuilder.getDOMImplementation().createDocument(
null, “order”, null);
Element oOrderElement = oDocument.getDocumentElement();
Element oLineItem = oDocument.createElement( “line_item” );
oLineItem.setAttribute( “name”, “T-shirt” );
oLineItem.setAttribute( “count”, “1” );
oLineItem.setAttribute( “color”, “red” );
oLineItem.setAttribute( “size”, “XL” );
Element oNoteElement = oDocument.createElement( “notes” );
Text oNoteText =
oDocument.createTextNode( “Please ship before next week.” );
oNoteElement.appendChild( oNoteText );
oLineItem.appendChild( oNoteElement );
oOrderElement.appendChild( oLineItem );
//--- Print out the document using a null XSL transformation.
Transformer oTransformer =
TransformerFactory.newInstance().newTransformer();
oTransformer.transform(
new DOMSource( oDocument ),
new StreamResult( System.out ) );
// --- Parse the order.xml document. ---
oDocument = oBuilder.parse( new File( “order.xml” ) );
// --- Document is parsed now. ---
System.out.println( “document is now: “ + oDocument );
}
catch( Exception e ) {
e.printStackTrace();
}
}
}

To compile the example, run the following command:

javac jdk14_dom_test.java

To run the program, use the following command:

java jdk14_dom_test

The example will output the state of the XML document as the program executes. First, the XML document is created. Then, the program writes the XML to disk. Finally, it parses the newly written file to reconstruct the XML document. The DOM interface gives us fairly complete control over parsing and manipulating XML in Java. For a standard interface, it’s quite good, but it forces us to do a lot of same tasks over and over. This is where JDOM and
dom4j shine in simplifying the model.