Welcome Guest!
Create Account | Login
Locator+ Code:

Search:
FTPOnline
Channels Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed

email article
printer friendly
get the code
more resources

A Better XML API for Java
The JDOM API provides the best of SAX and DOM for working with XML from Java
by Kevin Jones

Two APIs are widely used when parsing, creating, and managing XML in Java: SAX and DOM. Because it is fast and lightweight, SAX is great for consuming XML and performing tasks based on that XML. However, SAX does not allow for the in-memory manipulation of XML. DOM, on the other hand, allows programmers to create and manipulate XML in memory, storing the XML as a tree of information. DOM, however, is memory hungry and considered by many to be over-engineered. To address the problems of the DOM programming model, Jason Hunter and Brett McLaughlin proposed another Java API—JDOM—that is intended to be fast, lightweight, and easy to program.

The first thing to realize about JDOM is that it is not a parser. It relies on a SAX or DOM parser to build the JDOM representation. JDOM provides an API that allows easy creation and manipulation of XML from Java. For example, JDOM relies on the Java2 collection classes when returning collections of elements, unlike DOM, which has defined its own interfaces. JDOM, again unlike DOM, is very strongly typed. In DOM you have a common interface (org.w3c.dom.Node); everything inherits from it. In JDOM there is no common interface; everything is its own unique type—the org.jdom.Element interface represents all elements.

In JDOM the org.jdom.Document class represents an XML document. This class contains methods to create a document, add information items to a document, and remove information items from a document:

Document addContent(Comment comment) 
Document addContent(
	ProcessingInstruction pi) 
List getContent() 
DocType getDocType() 
Element getRootElement() 
boolean removeContent(
	Comment comment) 
boolean removeContent(
	ProcessingInstruction pi) 
Document setContent(List newContent) 
Document setDocType(DocType docType) 
Document setRootElement(
	Element rootElement)

There are two ways you can create an org.jdom.Document. Either an Infoset already exists (an XML file maybe), in which case a JDOM document can be built from that Infoset, or the document has to be created in memory as part of the application's processing. Infosets exist in many physical forms; for example, XML in a file, or an XML stream sent over an HTTP connection to a Web server. Given an Infoset in one of these forms, converting it into a JDOM document is trivial.

Back to top

Printer-Friendly Version











Java Pro | Visual Studio Magazine | Windows Server System Magazine
.NET Magazine | Enterprise Architect | XML & Web Services Magazine
| | Discussions | Newsletters | FTP Home