Creating XML Documents with JDOM

Let’s begin with a simple JDOM program that creates this XML document:

<?xml version="1.0"?>
<GREETING>Hello JDOM!</GREETING>

Since all documents should have root elements, we’ll need to create the root GREETING element first, then use that element to create the document:

  Element root = new Element("GREETING");
  root.setText("Hello JDOM!");
  Document doc = new Document(root); 

Note

Initially the Element object is not associated with any Document. It is free-standing. This contrasts with DOM where all nodes are always part of some document. JDOM allows nodes to stand on their own if that’s useful. However, JDOM does not allow a node to be part of two documents at once. Before an Element can be transferred into a new Document it must first be detached from its old document using its detach() method.

You can reorder the method calls. For example, you might want to modify the root element after it’s been attached to the document like this:

  Element root = new Element("GREETING");
  Document doc = new Document(root);
  root.setText("Hello JDOM!");

You can even create the Document object first using a no-args constructor and then set its root element like this:

  Document doc = new Document();
  Element root = new Element("GREETING");
  root.setText("Hello JDOM!");
  doc.setRootElement(root);

In this case the document begins its life in a temporarily malformed state, and any attempt to do almost anything with it except set a root element or add content to the document’s prolog will fail with an java.lang.IllegalStateException.


Copyright 2001, 2002 Elliotte Rusty Haroldelharo@metalab.unc.eduLast Modified April 18, 2002
Up To Cafe con Leche