Wednesday, March 21, 2012

JDOM Parser to Read and Update XML

JDom is a java based library for processing XML.  It is light weight and fast. It is simple to use since it was designed for Java.

JDom Documents can be used with DOM tree or SAX events.
JDom Support XPath.

The following examples shows some common usecases with JDom such as
1) Update the value of a node in the xml
2) Print the xml from JDom Document
3) Get a particular Node using XPath


//Update the value of a node
Document doc = new SAXBuilder().build(new File(fileToProcess));
Element rootElement = doc.getRootElement();
Element book = rootElement.getChild("book").getChild("author")
.setText("Sidd");

//Print the xml
XMLOutputter outputter = new XMLOutputter();
outputter.output(doc, System.out);


// Get a particular Node useing XPath
XPath xPath = XPath.newInstance("/bookstore/book[bookid=$bookid]/bookid");
xPath.setVariable("bookid", "id1002");

Element guest = (Element) xPath.selectSingleNode(doc);

System.out.println(guest);


These example code is straight forward, the full code can be found on google code here.

No comments :

Post a Comment