How to modify XML file in Java – (JDOM Parser)

JDOM XML parser example to modify an existing XML file :

  1. Add a new element
  2. Update existing element attribute
  3. Update existing element value
  4. Delete existing element

1. XML File

See before and after XML file.

File : file.xml – Original XML file.


<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="1">
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>5000</salary>
  </staff>
</company>

Later, update above XML file via JDOM XML Parser.

  1. Add a new “age” element under staff
  2. Update the staff attribute id = 2
  3. Update salary value to 7000
  4. Delete “firstname” element under staff

File : file.xml – Newly modified XML file.


<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="2">
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>7000</salary>
    <age>28</age>
  </staff>
</company>

2. JDOM Example

JDOM parser to update or modify an existing XML file.


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;

public class ModifyXMLFile {
	public static void main(String[] args) {

	  try {

		SAXBuilder builder = new SAXBuilder();
		File xmlFile = new File("c:\\file.xml");

		Document doc = (Document) builder.build(xmlFile);
		Element rootNode = doc.getRootElement();

		// update staff id attribute
		Element staff = rootNode.getChild("staff");
		staff.getAttribute("id").setValue("2");

		// add new age element
		Element age = new Element("age").setText("28");
		staff.addContent(age);

		// update salary value
		staff.getChild("salary").setText("7000");

		// remove firstname element
		staff.removeChild("firstname");

		XMLOutputter xmlOutput = new XMLOutputter();

		// display nice nice
		xmlOutput.setFormat(Format.getPrettyFormat());
		xmlOutput.output(doc, new FileWriter("c:\\file.xml"));

		// xmlOutput.output(doc, System.out);

		System.out.println("File updated!");
	  } catch (IOException io) {
		io.printStackTrace();
	  } catch (JDOMException e) {
		e.printStackTrace();
	  }
	}
}
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
newest oldest most voted
Chandan S R
Guest
Chandan S R

Hi mkyong,
It was a wonderful explanation. But I have one question for you.
Whenever I tried to add a new element into the XML file it was created in a single row, any idea how to populate each child of an element in a new line.
Thank you.

gordao00
Guest
gordao00

what if I want to add a company parent.
For example:

bcmoney
Guest
bcmoney

This example doesn’t seem to work for me… I’m getting the following errors: java.lang.NullPointerException at device.model.ModifyXMLFile.main(ModifyXMLFile.java:45) This error occurs on the line which looks for an “id” attribute in the Staff XML. After commenting out the attribute re-writing code, I still get: Exception in thread “main” org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. at com.sun.org.apache.xerces.internal.dom.NodeImpl.insertBefore(NodeImpl.java:478) at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(NodeImpl.java:235) at device.model.ModifyXMLFile.main(ModifyXMLFile.java:51) Java Result: 1 Seems odd I can’t get this basic example working, might make more sense to finally switch from traditional SAX/DOM to the much faster and easier to troubleshoot VTD-XML

bcmoney
Guest
bcmoney

XML File: yong mook kim mkyong 100000 ————————— JAVA FILE: import java.io.File; import java.io.FileReader; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author copelandb */ public class ModifyXMLFile { public static void main(String argv[]) throws Exception { try { String filepath = "./template/staff.xml"; //ONLY added a simple file reader to list the contents of the XML before changing FileReader fr = new FileReader(filepath); int ch; do { ch = fr.read(); if (ch != -1) System.out.print((char)… Read more »

bcmoney
Guest
bcmoney

XML File one more time (got escaped in the post): <?xml version=”1.0″ encoding=”UTF-8″ standalone=”no”?> <company> <staff id=”1″> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary> </staff> </company> (if this didn’t work, its just the same as the original)

trackback
Java XML Tutorials | J2EE Web Development Tutorials

[…] Modify XML file Example to modify XML attribute and element value. […]

Syed Ahmed Hussain
Guest
Syed Ahmed Hussain

I tried a billion times but it is not actually getting the file.
My filename is Study.xml and my path is D:\\Study.xml but still not working…
Can any one help please???

Linda
Guest
Linda

please help me to create node using the the same code

Thanks in advance

Linda

Linda
Guest
Linda

I tried the above example it’s working fine, could you please help me to create node.

Thanks in advance

Linda

Ragini
Guest
Ragini

THX A LOT.. your code helpd us a lot πŸ™‚

Blundell
Guest
Blundell

Thanks used this with WordML horibble markup! But this simplified the XML side, cheers

janliz
Guest
janliz

Does anyone show how to make use of this sample code to modify wordml file?
How to get the attribute of ?

ahaliav
Guest
ahaliav

thanks a lot you helped me!!

Natha
Guest
Natha

I got headache with xml update and I found ur codes.
Its work well and I wanna say thank you to u.
I really appreciate for your codes.
Thank you so much!
Best Regards,
kntsoe

Anand
Guest
Anand

Hi
I got one requirement where I have am geeting the XSD.I have to use xmlbean(for pojo class) and save the data by using Hibernate.I am new to both XMLbean and Hibernate.Please share any sample code based on xsd and xmlbean and hibernate.

Thanks in Advance

Vishnu
Guest
Vishnu

Thank you very much for the code. It is very useful for me. I am facing one problem with this code. The node value is not getting updated, but no error is shown. below is the code import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public static void main(String argv[]) { try{ String filepath = “c:\\testing.xml”; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); //Get the root element Node company; company =… Read more »

Avinash
Guest
Avinash

hi thanks i executed your code it is working fine.

gmarshall
Guest
gmarshall

This is great! Thank you very much for providing this. As a suggestion perhaps you could include an “add attribute” sample of code to your sample. Thanks again

Alberto Dousdebes
Guest
Alberto Dousdebes

Thanks a lot, i spend a long time trying to get my xml modified. With ur code and little modifications i could do it.

saharach.b
Guest
saharach.b

thank you.

Fakeyede Mobolaji
Guest
Fakeyede Mobolaji

Worked just fine. Thanks

Gordon
Guest
Gordon

Great example. How to add new attribute and element? Thanks!

expected result:

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="1">
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>5000</salary>
  </staff>
  <staff id="2">
    <firstname>tom</firstname>
    <lastname>tom lee</lastname>
    <nickname>tlee</nickname>
    <salary>7000</salary>
  </staff>
</company>
San
Guest
San

Hi,
I have a requirement for search and replace a value.
For e.g.,

Pls dont see the semantics, all I want is wherever the value “san” comes, i want to replace it with the value “raj” in all the places of the xml file.
PLs help me on this..

San
Guest
San

Hi,
I have a requirement for search and replace a value.
For e.g.,

<Company>
<Employee>
<Staff id="1" name="San"/>
<Staff id="2" name="San"/>
<Staff id="3" name="San"/>
</Employee>
</Company>

Pls dont see the semantics, all I want is wherever the value β€œsan” comes, i want to replace it with the value β€œraj” in all the places of the xml file.
PLs help me on this..

ben roggers
Guest
ben roggers

Thank you for very informative Java posts. I hope you continue to post for years to come! πŸ™‚

Vijit
Guest
Vijit

How do I add the same element as a child. I want something like this:

If I try to create a child element and add another child to it I get:

HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.

How can we generate the above XML tree?

Vijit
Guest
Vijit

How do I add the same element as a child. I want something like this: <family> <parent name = "P1"> <child name = "P1C1"> <child name = "P1C1C1"/> <child name = "P1C1C2"/> </child> <child name = "P1C2"/> <child name = "P1C3"> <child name = "P1C3C1"/> </child> </parent> <parent name = "P2"> <child name = "P2C1"> <child name = "P2C1C1"/> </child> <child name = "P2C2"> <child name = "P2C2C1"/> </child> </parent> </family> If I try to create a child element and add another child to it I get: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not… Read more »

maryam
Guest
maryam

hi,can you tell me how to write and remove from simple xml file in res/xml folder in android?I search that but I did not find

thanks in advance….

Heman
Guest
Heman

Here’s how… just found it…:

String placeForRes = "com.appname/res/values/strings.xml";
File source = new File(placeForRes);
junaid
Guest
junaid

Thank you so mutch for this wonderful tutorial. It really Help.

Aniket
Guest
Aniket

Hello Sir,
I want following strucure:-

1
1
1

I want that for particular TransID notevalues to be incremented at runtime. And for new Transaction new TransID strucure must be generated.
Please help me, i am really stucked in it.

janliz
Guest
janliz

Does anyone show how to make use of this sample code to modify wordml file?
How to get the attribute of w:t ?

nalin
Guest
nalin

great work (y)