Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Modify XML File in Java using JDOM parser example

In the previous tutorial we show how to read an XML File using JDOM parser. In this tutorial we are going to see how to modify the contents of an XML File.
 
 
 
 
 
 
 
 
 
 
This is the XML File we are going to use for the demonstration.

testFile.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><company>

	<employee id="10">
		<firstname>Jeremy</firstname>
		<lastname>Harley</lastname>
        <email>james@example.org</email>
		<department>Human Resources</department>
		<salary>2000000</salary>
	    <address>34 Stanley St.©</address>

	</employee>

	<employee id="2">
		<firstname>John</firstname>
		<lastname>May</lastname>
		<email>john@example.org</email>
		<department>Logistics</department>
		<salary>400</salary>
	    <address>123 Stanley St.</address>
	</employee>

</company>

ModifyXMLFileWithJDOM.java:

package com.javacodegeeks.java.core;

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

public class ModifyXMLFileWithJDOM {

	private static final String xmlFilePath = "C:\\Users\\nikos7\\Desktop\\filesForExamples\\testFile.xml";

	public static void main(String[] args) {

		SAXBuilder saxBuilder = new SAXBuilder();
		File xmlFile = new File(xmlFilePath);

		try {
			Document document = (Document) saxBuilder.build(xmlFile);

			Element rootElement = document.getRootElement();

			Element employee = rootElement.getChild("employee");

			// update the value of an attribute
			employee.getAttribute("id").setValue("120");

			// delete an element
			employee.removeChild("address");

			// update an element's value
			employee.getChild("department").setText("Logistics");

			// add a new element
			Element phoneNo = new Element("phonenumber").setText("9120970912");
			phoneNo.setAttribute("location", "home");
			employee.addContent(phoneNo);

			XMLOutputter xmlOutput = new XMLOutputter();

			//update the file with nice XML formating  
			xmlOutput.setFormat(Format.getPrettyFormat());

			xmlOutput.output(document, new FileWriter(xmlFilePath));

			//you can use this to output the result in standard output for debugging purposeses
			// xmlOutput.output(doc, System.out);

			System.out.println("XML File successfully updated!");

		} catch (IOException io) {
			System.out.println(io.getMessage());
		} catch (JDOMException jdomex) {
			System.out.println(jdomex.getMessage());
		}
	}
}

Updated testFile.xml:

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <employee id="120">
    <firstname>Jeremy</firstname>
    <lastname>Harley</lastname>
    <email>james@example.org</email>
    <department>Logistics</department>
    <salary>2000000</salary>
    <phonenumber location="home">9120970912</phonenumber>
  </employee>
  <employee id="2">
    <firstname>John</firstname>
    <lastname>May</lastname>
    <email>john@example.org</email>
    <department>Logistics</department>
    <salary>400</salary>
    <address>123 Stanley St.</address>
  </employee>
</company>

 
This was an example on how to modify the contents of an XML File using JDOM.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books