How to parse xml in java using jdom library
How to parse xml in java using jdom library
Favorites
Tags
Archive
Introduction
JDOM is an open source, Java-based library to parse XML documents. It is
typically a Java developer friendly API. It is Java optimized and it uses Java
collections like List and Arrays.
JDOM works with DOM and SAX APIs and combines the best of the two. It is of
low memory footprint and is nearly as fast as SAX.
You need to move parts of an XMl document around (you might want to sort
certain elements, for example).
You need to use the information in an XML document more than once.
You are a Java developer and want to leverage Java optimized parsing of
XML.
Advantages
Following are the advantages of JDOM parser −
JDOM classes
JDOM defines several Java classes. Here are the most common classes −
Class Description
JDOM Methods
When you are working with JDOM, there are several methods you'll use often −
Class Description
Node.getChildren(Name) Get all the direct child nodes with a given name.
Node.getChild(Name) Get the first child node with the given name.
Parsing
In order to parse an xml file you need a parser. JDom parser is the one i will be
using. There are 4 steps involved in parsing an xml file to retrieve its elements.
They are:
4. Retriving Elements
Retrieving Elements
After following the first three steps, we have successfully build JDOM document
from our XML file or stream. We can now use methods available in Document and
Element classes to obtain all the related information from the document.
The getName() method on Element object returns the name of the element in the
form of a String.
The getValue() method on an Attribute object retrieves the value of the attribute
as textual content.
Query By Attribute
Elements can also have attributes along with the text content. Now, let use the
same cars.xml file to query the carname elements by their company attribute.
if(student.getAttributeValue("rollno").equals("393")){
found = true;
break;
}
}
if(found){
The steps involved ini creating an xml file using JDOM are:
RootElement.addContent(newElement);
Creating Attributes
we see how to create elements along with their attributes and attach them to the
root. The setAttribute() method on each element sets the attribute and setText()
method is used to set the text content of each element.
try{
Document doc = new Document();
//Root Elemenet
Element carsElement = new Element("cars");
doc.setRootElement(carsElement);
//Other Elements
Element supercarEle = new Element("supercars");
supercarEle.setAttribute("company","Ferrari");
try {
SAXBuilder saxBuilder = new SAXBuilder();
File inputFile = new File("college.xml");
staffcount.setText("15");break;
}
}