O'Reilly logo

Java and XML by Brett McLaughlin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting a Document

The first task in any process involving JDOM is to obtain a JDOM Document object. The Document object in JDOM is the core class that represents an XML document.

Note

Like all other objects within the JDOM model, the org.jdom.Document class is detailed in Appendix A, and all its method signatures are listed. Additionally, complete Javadoc on JDOM is available at http://www.jdom.org.

There are two ways to obtain a JDOM Document object: create one from scratch, when no existing XML data must be read, and build one from existing XML data.

Starting from Scratch

When no existing XML data is needed as a starting point, creating a JDOM Document is simply a matter of invoking a constructor:

Document doc = new Document(new Element("root"));

As we mentioned earlier, JDOM is a set of concrete classes, not a set of interfaces. This means that the more complicated code using factories to create objects as needed to create an org.w3c.dom.Element in DOM is unnecessary in JDOM. We simply perform the new operation on the Document object, and we have a viable JDOM Document that can be used.

This Document is not tied to any particular parser, either. XML often needs to be created from a blank template, rather than an existing XML data source, so there is a JDOM constructor for org.jdom.Document that requires only a root Element as a parameter. Example 8.3 builds an XML document from scratch using JDOM.

Example 8-3. Building a Document

import org.jdom.Document; import org.jdom.Element; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required