Reading an XML document using JDOM

This Example shows you how to Read an
XML document by using JDOM.eplace a node with existing node in a DOM document.
JDOM is used for parsing, creating, manipulating, and serializing XML
documents, it is a tree based Java api. JDOM represents an XML document as a
tree composed of elements, attributes, comments, processing instructions, text
nodes. JAXP (Java API for XML Processing) is an interface which provides
parsing of xml documents. Here the Document BuilderFactory is used to create
new DOM parsers.These are some of the methods used in code given below for
reading an XML document using JDOM:-
SAXBuilder builder = new SAXBuilder():-SAXBuilder
is a class that bulids a JDOMDocument from file,stream,reader etc.Here we are
creating SAXbuilder object which is used to Builds a JDOM document from files.
Element root = document.getRootElement():-Through
this method we can have direct access to the root of the DOM document.
List row =
root.getChildren("Companyname"):-List is an Interface through which
we have a precise control over each element inserted in the List.Here we have
created interface row which has precise control over each element inserted in
the List.
String name =
Employee.getAttribute("name").getValue():-This is a method thats
gets an attribute value by name.
ReadingxmlusingJdom.java
/*
* @Program to read an XML document using JDOM?
* ReadingxmlusingJdom.java
* Author:-RoseIndia Team
* Date:-10-Jun-2008
*/
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import java.io.ByteArrayInputStream;
import java.util.List;
public class ReadingxmlusingJdom {
public static void main(String[] args) throws Exception {
String data =
"<root>" +
"<Companyname>" +
"<Employee name=\"Girish\" Age=\"25\">Developer</Employee>" +
"</Companyname>" +
"<Companyname>" +
"<Employee name=\"Komal\" Age=\"25\">Administrator</Employee>" +
"</Companyname>" +
"</root>";
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new ByteArrayInputStream(data.getBytes()));
Element root = document.getRootElement();
List row = root.getChildren("Companyname");
for (int i = 0; i < row.size(); i++) {
Element Companyname = (Element) row.get(i);
List column = Companyname.getChildren("Employee");
for (int j = 0; j < column.size(); j++) {
Element Employee = (Element) column.get(j);
String name = Employee.getAttribute("name").getValue();
String value = Employee.getText();
int length = Employee.getAttribute("Age").getIntValue();
System.out.println("Name = " + name);
System.out.println("Profile = " + value);
System.out.println("Age = " + length);
}
}
}
} |
Output of the program:-
Name = Girish
Profile = Developer
Age = 25
Name = Komal
Profile = Administrator
Age = 25
|
Download Source Code

|