Java Tutorial - Java Script : Processing XML with XOM

Java Tutorial - Java Script :
 Processing XML with XOM
After you have downloaded XOM and added its packages to your system’s Classpath, you’re ready to begin using XOM.

The full installation instructions are available from the XOM and Xerces websites. The classes are distributed as JAR archive files—xom-1.1.jar, xercesImpl.jar, and xmlapis. jar. These files should be added to your system’s Classpath environment variable so that your Java programs can use XOM classes.

Creating an XML Document

The first application you will create, RssWriter, creates an XML document that contains the start of an RSS feed. The document is shown in Listing 19.2.
The base nu.xom package contains classes for a complete XML document (Document) and the nodes a document can contain (Attribute, Comment, DocType, Element, ProcessingInstruction, and Text).

The RssStarter application uses several of these classes. First, an Element object is created by specifying the element’s name as an argument:

Element rss = new Element(“rss”);



This statement creates an object for the root element of the document, rss. Element’s one-argument constructor can be used because the document does not employ a feature of XML called namespaces; if it did, a second argument would be necessary: the namespace uniform resource identifier (URI) of the element. The other classes in the XOM
library support namespaces in a similar manner.

In the XML document in Listing 19.2, the rss element includes an attribute named version with the value “2.0”. An attribute can be created by specifying its name and value in consecutive arguments:

Attribute version = new Attribute(“version”, “2.0”);

Attributes are added to an element by calling its addAttribute() method with the attribute as the only argument:

rss.addAttribute(version);

The text contained within an element is represented by the Text class, which is constructed by specifying the text as a String argument:

Text titleText = new Text(“Workbench”);

When composing an XML document, all of its elements end up inside a root element that is used to create a Document object—a Document constructor is called with the root element as an argument. In the RssStarter application, this element is called rss. Any Element object can be the root of a document:

Document doc = new Document(rss);

In XOM’s tree structure, the classes representing an XML document and its constituent parts are organized into a hierarchy below the generic superclass nu.xom.Node. This class has three subclasses in the same package: