Java Reference
In-Depth Information
Example 19−5: DOMTreeWalkerTreeModel.java (continued)
frame.setVisible(true);
}
}
The JDOM API
Until now, this chapter has considered the official, standard ways of parsing and
working with XML documents: DOM is a standard of the W3C, and SAX is a de
facto standard by virtue of its nearly universal adoption. Both SAX and DOM were
designed to be programming language-independent APIs, however. This generality
means they can't take full advantage of the features of the Java language and plat-
form, however. As I write this chapter, there is a new (still in beta release) but
promising API targeted directly at Java programmers. As its name implies, JDOM is
an XML document object model for Java. Like the DOM API, it creates a parse tree
to represent an XML document. Unlike the DOM, however, the API is designed
from the ground up for Java and is significantly easier to use than the DOM. JDOM
is an open-source project initiated by Brett McLaughlin and Jason Hunter, who are
the authors of the O'Reilly topics Java and XML and Java Servlet Programming ,
respectively.
Example 19-6 shows how the JDOM API can be used to parse an XML document,
to extract information from the resulting parse tree, to create new element nodes
and add them to the parse tree, and, finally, to output the modified tree as an XML
document. Compare this code to Example 19-3; the examples perform exactly the
same task, but as you'll see, using the JDOM API makes the code simpler and
cleaner. You should also notice that JDOM has its own built-in XMLOutputter class,
obviating the need for the XMLDocumentWriter shown in Example 19-4.
Example 19−6: WebAppConfig2.java
package com.davidflanagan.examples.xml;
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
/**
* This class is just like WebAppConfig, but it uses the JDOM (Beta 4) API
* instead of the DOM and JAXP APIs
**/
public class WebAppConfig2 {
/** The main method creates and demonstrates a WebAppConfig2 object */
public static void main(String[] args)
throws IOException, JDOMException
{
// Create a new WebAppConfig object that represents the web.xml
// file specified by the first command-line argument
WebAppConfig2 config = new WebAppConfig2(new File(args[0]));
// Query the tree for the class name associated with the servlet
// name specified as the 2nd command-line argument
System.out.println("Class for servlet " + args[1] + " is " +
Search WWH ::




Custom Search