Searching...
Wednesday, 19 September 2012

Java XML JDOM Modify XML Example

04:35

What is JDOM ?

JDOM is an open source Java-based document object model for XML that was designed specifically for the Java platform so that it can take advantage of its language features. JDOM integrates with Document Object Model (DOM) and Simple API for XML (SAX), supports XPath and XSLT. It uses external parsers to build documents.

JDOM Readng XML Example

Create a Maven project and update below dependency

<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>

Sample xml files to modify

<?xmlversion="1.0"encoding="UTF-8"?>
<Order>
<OrderNumber number="1000">
<OrderItem>Phone</OrderItem>
<OrderItemDescription>Smart phone</OrderItemDescription>
<OrderItemPrice>7000</OrderItemPrice>
<OrderItemTax>700</OrderItemTax>
<OrderItemDiscount>700</OrderItemDiscount>
<OrderItemTotal>5600</OrderItemTotal>
</OrderNumber>
</Order>
Create Java file to modify  XML file

package mycollectiontest;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import java.io.*;

public class XMLExample {

public static void main(String[] args) {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("orderSample.xml");
try {
Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();

// Updating OrderNumber attribute
Element orderNumber = rootNode.getChild("OrderNumber");
orderNumber.getAttribute("number").setValue("1002");

// Adding new Element OrderCoupon
Element orderCoupon = new Element("orderCoupon").setText("NEWYEAROFFER");
orderNumber.addContent(orderCoupon);

// Updating OrderItemPrice
orderNumber.getChild("OrderItemPrice").setText("10000");

// Removing OrderItemDiscount element
orderNumber.removeChild("OrderItemDiscount");

XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(document, new FileWriter("orderSample.xml"));

System.out.println("orderSample.xml...Updated");
} catch (IOException ioException) {
System.out.println(ioException.getMessage());
} catch (JDOMException jdomException) {
System.out.println(jdomException.getMessage());
}
}

}

Output

<?xmlversion="1.0"encoding="UTF-8"?>
<Order>
<OrderNumber number="1002">
<OrderItem>Phone</OrderItem>
<OrderItemDescription>Smart phone</OrderItemDescription>
<OrderItemPrice>10000</OrderItemPrice>
<OrderItemTax>700</OrderItemTax>
<OrderItemTotal>5600</OrderItemTotal>
<orderCoupon>NEWYEAROFFER</orderCoupon>
</OrderNumber>
</Order>

0 comments: