Access and Manipulate Elements of XML file Using Jdom

It has been long time since I updated my blog, challenging the very definition of blog.Anyway lately I’ve been doing some XML parsing for a new project using Java.I used the default “document Object Model” and it gave me tough time.Reading elements was not not tough , but manipulating and generating new xml file was somewhat difficult.Then came jdom to my rescue after using the Big G (Google).So, now it’s time to share something I gained from open source community.Jdom is simply “document object model” based on java for representing XML documents which is an alternative to DOM and SAX.Jdom uses JAXP parser by default rather than crimson or any other parser.But, it can work with nearly every other parser and integrate very well with DOM and SAX.


In order to use the Jdom API, you need to add the jar file to the used library.In case of JBuilder IDE, you can add the jar file by going to Project, then Project Properties and at last Required Library tab.For Eclipse go to Project, Properties, Java Build Path, library tab and add the jar file.

Here, I’ll be providing a sample program that checks whether an element is present or not in a XML file.Then, it will add the element with default node value “1” in case it is not present or increment the value by “1” in case of presence.You will see that SAX events of SAXBuilder class is used in this program and getPrettyformat of Format class is used for white space beautification.I’ve put comments in the code, because my C++ instructor used to say “The best way to punish a programmer is to give him code written by someone else“.

The sample XML file used in this example :

xml version=”1.0″ encoding=”UTF-8″?>


h3r3 and th3re

something n3rdy
too lazy to think

package dev.preetish;

import java.io.FileWriter;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class xmlParser
{
/* This method is used to manipulate the element node value  */
private void updateXML()
{
try
{
String xmlPath = “D:” + File.separator + “devArea” + File.separator + “sample.xml”;
File xmlFile = new File(xmlPath);

/*  The SAXBuilder class is initialised here */
SAXBuilder builder = new SAXBuilder();

if (file.exists())
{
/* Creating instance of Document class and building a document from given file using method build */
Document document = (Document) builder.build(xmlFile);
/* Getting the Root element from Document class instance */
Element rootEle = document.getRootElement();
/* Getting the child element from the root Element and getting their child element */
Element firstEle = rootEle.getChild(“FIRSTELEMENT”);
/* Checking whether ADDON element is present or not*/
Element addOn = firstEle.getChild(“ADDON”); /* Returns null if element is not present */

if (addon != null) {
 /* Getting value of addon element*/
 String addCounter = addon.getValue();
 /* Incrementing value by 1 */
 int add_counter=Integer.parseInt(addCounter)+1;
 /* Setting value of the node */
 addon.setText(Integer.toString(add_counter));

}
 else {
 /*Adding new element ADDON */
   Element make = new Element(“ADDON1”);
   make.addContent(“1”);
   firstEle.addContent(make);

 }
/* Printing after manipulation of XML document and using getPrettyFormat method of Format class for white space beautification */
String  newXmlFile= new XMLOutputter(Format.getPrettyFormat()).outputString(document);
System.out.println(“XML file after Manipulation : ” + “\n”+xmlFileData);
/* Modify the orginal document using FileWriter */
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(newXmlFile);
fileWriter.close();
}
else
{
System.out.println(“File does not exist”);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

public static void main(String argS[])
{
try
{
new xmlParser().updateXML();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Happy XML parsing !!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *