Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

How to parse xml in java using jdom library

The document provides a comprehensive guide on using JDOM, a Java-based library for parsing XML documents, detailing its advantages, classes, methods, and steps for parsing, querying, creating, and modifying XML. It emphasizes the developer-friendly API and low memory footprint of JDOM while explaining how to manipulate XML elements and attributes effectively. The document also includes code examples for practical implementation of these concepts.

Uploaded by

Jonah Arthur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

How to parse xml in java using jdom library

The document provides a comprehensive guide on using JDOM, a Java-based library for parsing XML documents, detailing its advantages, classes, methods, and steps for parsing, querying, creating, and modifying XML. It emphasizes the developer-friendly API and low memory footprint of JDOM while explaining how to manipulate XML elements and attributes effectively. The document also includes code examples for practical implementation of these concepts.

Uploaded by

Jonah Arthur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Parsing XML With JDOM

Favorites

Notebook Data Access

Tags

Last edited time @March 15, 2025 11:35 AM

Archive

Created time @October 15, 2024 10:32 PM

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.

When to Use JDOM parser?


You should use a JDOM parser when −

Parsing XML With JDOM 1


You need to know a lot about the structure of an XML document.

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.

What is the result of Parsing?


When you parse an XML document with a JDOM parser, you get the flexibility to
get back a tree structure that contains all of the elements of your document
without impacting the memory footprint of the application.
JDOM provides a variety of utility functions that you can use to examine the
contents and structure of an XML document in case the document is well
structured and its structure is known.

Advantages
Following are the advantages of JDOM parser −

Developer friendly API.

Flexible and easily maintainable.

Lightweight and quick API

Well integrates with DOM and SAX standards.

JDOM classes
JDOM defines several Java classes. Here are the most common classes −

Class Description

Represents an entire XML document. A Document object is often referred


Document
to as a DOM tree.

Represents an XML element. Element object has methods to manipulate


Element
its child elements, its text, attributes, and namespaces.

Represents an attribute of an element. Attribute has method to get and


Attribute
set the value of attribute. It has parent and attribute type.

Parsing XML With JDOM 2


Text Represents the text of XML tag.

Comment Represents the comments in a XML document.

JDOM Methods
When you are working with JDOM, there are several methods you'll use often −

Class Description

SAXBuilder.build(xmlSource) Build the JDOM document from the xml source.

Document.getRootElement() Get the root element of the XML.

Element.getName() Get the name of the XML node.

Element.getChildren() Get all the direct child nodes of an element.

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:

1. Creating A SAXBuilder object

2. Reading the XML

3. Parsing the XML

4. Retriving Elements

Creating A SaxBuilder Object


JDom document is built using a sax builder.

Parsing XML With JDOM 3


SAXBuilder saxbuilder = new SAXBuilder();

Reading The File


We use the File class to load the xml file .

File xmlfile = new File("student.xml");

Parsing The XML DOCUMENT


Using build() function, we parse an XML file or input stream. It builds the JDOM
document from the given file or input stream. It throws JDOMException and
IOException when there are errors in parsing the document.

Document document = saxbuilder.build(xmlfile);

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.

Retrieving Root Element


The method getRootElement() of Document interface returns the root element of
the document in the form of an Element object.

The getName() method on Element object returns the name of the element in the
form of a String.

Parsing XML With JDOM 4


Document document = saxbuilder.build(xmlfile);
Element root_element = document.getRootElement();
System.out.println("Root Element Name : " + root_element.getName());

Retrieving Child Elemets And Atrributes


To retrieve child elements of an element, getChildren() method is used on the
Element object. It returns the child elements in the form of a list. This list contains
all the child elements in the of Element objects.

To retrieve text content of an element, getText() method is used on the Element


object. It returns the content between the opening and closing tags of an Element.

The getAttribute("attr_name") method on an Element object takes attribute name


as an argument and retrieves the attribute in the form of Attribute object. If there is
no such attribute in an element, it returns null.

The getValue() method on an Attribute object retrieves the value of the attribute
as textual content.

//Retrieving Child Elements


List<Element> studentList = root_element.getChildren();
System.out.println("----------------------------");

for(int temp = 0; temp<studentList.size(); temp++){


Element student = studentList.get(temp);

System.out.println("\nCurrent Element: " + student.getName());


Attribute attribute = student.getAttribute("rollno");
System.out.println("Student roll no: " + attribute.getValue());
System.out.println("First Name: " + student.getChild("firstname").getTe
System.out.println("Last Name: " + student.getChildText("lastname"));
System.out.println("NickName: " + student.getChildText("nickname"));

Parsing XML With JDOM 5


System.out.println("Marks: " + student.getChild("marks").getValue());
}

Query XML Using JDOM


The steps to follow to query xml documents are:

1. Creating a SAXBuilder Object

2. Reading the XML

3. Parsing the XML Document

4. Querying the Elements

Querying by Text Content


We can query elements by their text content, by first getting the root element
using getRootElement() method. After we obtain the root element, we can use
getChildren() function to get all the child elements. Then, we can query the
elements by text content using getText() method.

Element rootElement = xmldocument.getRootElement();


List<Element> children = rootElement.getChildren("student");

boolean found = false;


for(int i = 0; i < children.size(); i++){
Element student = children.get(i);
if(student.getChild("firstname").getText().equals("dinkar")){
found = true;
break;
}
}
if(found){
System.out.println("Student found");
}else{

Parsing XML With JDOM 6


System.out.println("Failed to find the queried student");
}

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.

The getAttributeValue("attr_name") method of Element class takes attribute


name as a String argument and returns the corresponding value of the attribute.

Element rootElement = xmldocument.getRootElement();


List<Element> children = rootElement.getChildren("student");

boolean found = false;


for(int i = 0; i < children.size(); i++){
Element student = children.get(i);

if(student.getAttributeValue("rollno").equals("393")){
found = true;
break;
}
}
if(found){

System.out.println("The Value Was Found");


}else{
System.out.println("The Value Was Not Found");
}

Creating XML using JDOM

Parsing XML With JDOM 7


Java JDOM Parser is a Java API that has classes and methods to create XML
documents from scratch. We can create a new JDOM document object and add
elements, attributes using the methods available in Document and Element
interfaces. In this chapter, we are going to use setRootElement(), addContent(),
setText() and setAttribute() methods to create XML files in detail.

The steps involved ini creating an xml file using JDOM are:

Step 1: Creating JDOM Document object

Step 2: Creating and appending Root Element

Step 3: Creating elements and attributes

Step 4: Appending Elements to Root

Step 5: Writing the content into XML file

Step 6: Testing the output using console

Creating JDOM Document Object


The org.jdom2 package has Document class. It represents the XML document.
This class has methods to access the root element and also the document level
information.

Document doc = new Document();

Creating And Appending The Root Element


An XML document must contain a root element. We create root element using
Element class of org.jdom2 package. If we provide a String to the constructor, it
creates element with that supplied local name.
The setRootElement() method in the Document class sets the root of the
document. This method takes Element as an argument and sets it as the root. If
the root element is already present, the old root Element gets replaced with this
supplied Element.

Parsing XML With JDOM 8


Element RootElement = new Element("root");
doc.setRootElement(RootElement);

Creating Elements And Attributes


We can create Elements the same way we created root element in the previous
step. To set an attribute to the Element, we use setAttribute() method

Element newElement = new Element("FirstElement");


newElement.setAttribute("attr_name","attr_value");

Appending Elements To Root


The Elements created in the previous step are now attached to the root element
using addContent() method. This method takes single element or collection of
elements in the form of content list and adds them to the element accordingly.

RootElement.addContent(newElement);

Writing The Content Into XML File


The TransformerFactory class is used to create a new instance of Transformer
object. Using the transform() function in Transformer class, source is transformed
to the destination result. We are creating JDOMSource object by passing
document as a parameter.

TransformerFactory transformerFactory = TransformerFactory.newInstance();


Transformer transformer = transformerFactory.newTransformer();
JDOMSource source = new JDOMSource(doc);
StreamResult result = new StreamResult(new File("newFile.xml"));
transformer.transform(source, result);

Parsing XML With JDOM 9


Test The OutPut
This is an optional step used for testing purpose. To print the output on the
console, an XMLOutputter object is created and the Document object is passe

XMLOutputter xmlOutput = new XMLOutputter();


xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, System.out);

//Creating JDOM Document


Document doc = new Document();

//Creating Root Element


Element rootele = new Element("Cars");
rootele.setText("Ferrari");
doc.setRootElement(rootele);

//Writing The content into xml file


TransformerFactory transformerFactory = TransformerFactory.newInstance
Transformer transformer = null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
throw new RuntimeException(e);
}

JDOMSource source = new JDOMSource(doc);


StreamResult result = new StreamResult(new File("cars.xml"));
try {
transformer.transform(source,result);
} catch (TransformerException e) {
throw new RuntimeException(e);
}
XMLOutputter xmlOutputter = new XMLOutputter();

Parsing XML With JDOM 10


xmlOutputter.setFormat(Format.getPrettyFormat());
try {
xmlOutputter.output(doc,System.out);
} catch (IOException e) {
throw new RuntimeException(e);
}

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");

Element carEle1 = new Element("carname");


carEle1.setAttribute("type","formula one");
carEle1.setText("ferrar 101");

Element carEle2 = new Element("carname");


carEle2.setAttribute("type","sports");
carEle2.setText("Ferrari 202");

Parsing XML With JDOM 11


supercarEle.addContent(carEle1);
supercarEle.addContent(carEle2);

//Appending Elements To Root


carsElement.addContent(supercarEle);

TransformerFactory transformerFactory = TransformerFactory.newInstance


Transformer transformer = transformerFactory.newTransformer();
JDOMSource source = new JDOMSource(doc);
StreamResult result = new StreamResult(new File("carsele.xml"));
transformer.transform(source,result);

XMLOutputter xmlOutputter = new XMLOutputter();


xmlOutputter.setFormat(Format.getPrettyFormat());
xmlOutputter.output(doc,System.out);

}catch (Exception e){


e.printStackTrace();
}

Modifying XML Documents


We can use setText() to modify content and addContent() to add new elements.
The steps involved in modifying an xml document includes

Step 1: Creating a SAXBuilder Object

Step 2: Reading the XML

Step 3: Parsing the XML Document

Step 4: Updating the content of XML document

Step 5: Writing the content into XML file

Step 6: Output to console for testing

Parsing XML With JDOM 12


Updating Text Content
To update text content of any element, we can use the setText() method of
Element class. This method takes the text content as an argument in the form of a
String. If text content already exists, it updates the old one with the new text
content.

try {
SAXBuilder saxBuilder = new SAXBuilder();
File inputFile = new File("college.xml");

Document doc = saxBuilder.build(inputFile);


Element rootelement = doc.getRootElement();

List<Element> deptlist = rootelement.getChildren("department");

for(int i = 0 ; i < deptlist.size(); i++){


Element department = deptlist.get(i);
if(department.getAttributeValue("id").equals("103")){
Element staffcount = department.getChild("staffCount");

staffcount.setText("15");break;
}
}

TransformerFactory transformerFactory = TransformerFactory.newInstanc


Transformer transformer = transformerFactory.newTransformer();
JDOMSource source = new JDOMSource(doc);
StreamResult result = new StreamResult(new File("college.xml"));
transformer.transform(source, result);

//Output to console for testing


XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());

Parsing XML With JDOM 13


xmlOutput.output(doc, System.out);

}catch (Exception e){


e.printStackTrace();
}

public static void AddProducte(String CaixaID, Producte p, String fileName) {


try {
SAXBuilder sAXBuilder = new SAXBuilder();
FileInputStream fis = new FileInputStream(new File(fileName));
Document doc = sAXBuilder.build(fis);
Element rootelement = doc.getRootElement();

// Find the caja by ID


Element caixachild = rootelement.getChild("caixes");
List<Element> cajas = caixachild.getChildren("caja");

for (Element caja : cajas) {


if (caja.getAttributeValue("id").equals(CaixaID)) {
// Create a new product element
Element newProduct = new Element("product");
newProduct.setAttribute("fragibilidad", String.valueOf(p.isIsfragil()));

// Add child elements for the new product


Element nameElement = new Element("name");
nameElement.setText(p.getName());
newProduct.addContent(nameElement);

Element priceElement = new Element("price");


priceElement.setText(String.valueOf(p.getPrice()));
newProduct.addContent(priceElement);

Element sizeElement = new Element("tamano");


sizeElement.setText(p.getSize().toString()); // Assuming MIDA is an enu

Parsing XML With JDOM 14


newProduct.addContent(sizeElement);

// Append the new product to the Products element


Element productes = caja.getChild("Products");
productes.addContent(newProduct);

// Output the modified document back to the file


XMLOutputter xMLOutputter = new XMLOutputter();
xMLOutputter.setFormat(Format.getPrettyFormat());
xMLOutputter.output(doc, new FileOutputStream(fileName));
break; // Exit the loop after adding the product
}
}

} catch (FileNotFoundException ex) {


Logger.getLogger(ModificacionJDOM.class.getName()).log(Level.SEVERE, n
} catch (JDOMException ex) {
Logger.getLogger(ModificacionJDOM.class.getName()).log(Level.SEVERE, n
} catch (IOException ex) {
Logger.getLogger(ModificacionJDOM.class.getName()).log(Level.SEVERE, n
}
}

Parsing XML With JDOM 15

You might also like