Creating XML Documents with JDOM


Let's begin with a simple JDOM program that creates the following XML document:

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

As 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 freestanding. This contrasts with DOM, which requires that 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 has been attached to the document, as follows :

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

You can even create the Document object first by using a no-args constructor and then setting its root element, as follows:

 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 a java.lang.IllegalStateException .



Processing XML with Java. A Guide to SAX, DOM, JDOM, JAXP, and TrAX
Processing XML with Javaв„ў: A Guide to SAX, DOM, JDOM, JAXP, and TrAX
ISBN: 0201771861
EAN: 2147483647
Year: 2001
Pages: 191

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net