Dom4j Modify a XML file

We saw about creating a XML with DOM4J in the previous post. In this post, we will see how to modify an existing XML using DOM4J. Make sure that you have the following JAR files with you before you start:

1) dom4j-1.6.1 -> you can grab this from the official website. Check out here.

2) jaxen-1.1.1 -> This is an open source XPATH library internally used in Dom4J. Grab the latest JAR file from the official website. Check out here for more details.

There are many ways to traverse a XML file. In this post, we will see how to make use of XPATH to traverse an XML and update the node values. For all the beginners, if you want to know what XPATH is and how to create XPATH, check out here.Now, let us assume that we have an XML as a string.
123234
The aim is to modify the values of a1 and a2 XML tags and create a new XML like this:
45453244
This post assumes that the XML is available as a string to you. Let us get started. Read the XML into a string to start with..
String text="123234";
Now, inorder to traverse this XML and make the alterations, the "string" needs to be convertedto a document object.
Document document=DocumentHelper.parseText(text);
Now we have the XML converted as a document object and we can traverse it to make the modification. and are nodes in the XML. To modify the value of , we need to fist retrive a1 into a node object. This can be done with the following piece of code.

Node node=document.selectSingleNode("//root/a1" );
This node retrieval must be handled in an try -- catch block, else it will result in an exception during compilation. Once we have retrieved the a1 node, changing the value is as simple like this:
node.setText("4545");
On similar lines for ,we need to give
Node node1=document.selectSingleNode("//root/a2" );
node1.setText("3244");
That is it, we are almost done. Refer to my previous post which tells how to write the XML to a file.The complete listing with the exception block is provided below:
try {
String text="123234";
Document document = DocumentHelper.parseText(text);
Node node=document.selectSingleNode("//root/a1" );
node.setText("4545");
Node node1=document.selectSingleNode("//root/a2" );
node1.setText("3244");
}
catch (Exception e1) {
e1.printStackTrace();
}   
Wrap this inside a method and import the required packages. You will be in need of the following
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
Invoke the write method and see your code in action! Any queries, post it..

1 comment:

  1. Have you looked at VTD-XML? it is 10x faster and 5x more memory efficent tha DOM4J or JDOM

    http://vtd-xml.sf.net

    ReplyDelete