If we had to examine a document that had more than one element with the same name, we could use the

getChildren()

method which returns a List containing all the matching elements. Using Java Collection API, we can iterate through the list of elements. Once again, the goal is to use familiar Java constructs (like a List) to simplify XML manipulations.

Creating XML

The objects representing the various parts of an XML document can be constructed independently of each other. These objects can then be tied together to form a hierarchy (nesting relationships). The important thing is that you have control and flexibility over how the various pieces are tied together allowing you to create XML documents from scratch while conforming to various DTDs. We demonstrate this using a servlet. The goals is to collect some information from an HTML form and then produce an XML document based on that information. Listing 4 shows the HTML form:

Listing 4.

Please provide the following information:

Name:

Favorite Food:

Favorite Sport:

Indoor
Outdoor

Listing 5 shows the servlet that handles the information provided by the above form:

method to insert the text information inside the element. We also create an Attribute and associate it with the "sport" element. Each element is created independently from others. We insert all of them into the root element (survey) using the

addContent()

method and use the constructor for Document to create the actual XML document object. The creation process is very straightforward. Using the other classes in the org.jdom package, we can independently create comments, CDATA sections, processing instructions, etc. and add them to the XML document.

We have tried to show some of the capabilities of JDOM through some simple examples. Hopefully it is clear to you that JDOM takes an intuitive approach to modeling an XML document into a series of Java objects. These objects are then used like any other Java object to manipulate and modify the XML document. Although JDOM does not have the language independence quality attributed to DOM and SAX, it does provide Java programmers with a simple way to write code for reading, writing and manipulating XML documents. Furthermore, by providing its output in XML, DOM tree and SAX event streams, JDOM does provide a bridge in cases where using a specific standard-based API is necessary. JDOM is evolving and future releases could include support for XSLT and XPath.

About the Author

Piroz Mohseni is president of Bita Technologies, which focuses on business improvement through effective usage of technology. His areas of interest include enterprise Java, XML, and e-commerce applications. Contact him at mohseni@bita-tech.com.