Information About

Jdom





EXAMPLES


Suppose the file "foo.xml" contains this XML document:







One can parse the XML file into a tree of Java objects with JDOM, like so:

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new FileInputStream("foo.xml"));
Element root = doc.getRootElement();
// root.getName() is "shop"
// root.getAttributeValue("name") is "shop for geeks"
// root.getAttributeValue("location") is "Tokyo, Japan"
// root.getChildren() is a java.util.List object who has 3 Element objects.

In case if you don't want to create the document object from any file or any input stream in that case you can create the document object against the element.

Element root = new Element("shop"); // here is the root
Document doc = new Document(root);

As a converse, one can construct a tree of elements, then generate a XML file from it, like:

Element root = new Element("shop");
root.setAttribute("name", "shop for geeks");
root.setAttribute("location", "Tokyo, Japan");
Element item1 = new Element("computer");
item1.setAttribute("name", "iBook");
item1.setAttribute("price", "1200$");
root.addContent(item1);
// do the similar for other elements
XMLOutputter outputter = new XMLOutputter();
outputter.output(new Document(root), new FileOutputStream ("foo2.xml"));


EXTERNAL LINKS