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

In this example, we demonstrate the use of DOM parser 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" standalone="no" ?> 
<company>
   <staff id="1">
	<firstname>yong</firstname>
	<lastname>mook kim</lastname>
	<nickname>mkyong</nickname>
	<salary>100000</salary>
   </staff>
</company>

Later, update above XML file via DOM XML Parser.

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

File : file.xml – Newly modified XML file.


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

2. DOM Parser

DOM XML parser to update an above XML file.


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 class ModifyXMLFile {

	public static void main(String argv[]) {

	   try {
		String filepath = "c:\\file.xml";
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(filepath);

		// Get the root element
		Node company = doc.getFirstChild();

		// Get the staff element , it may not working if tag has spaces, or
		// whatever weird characters in front...it's better to use
		// getElementsByTagName() to get it directly.
		// Node staff = company.getFirstChild();

		// Get the staff element by tag name directly
		Node staff = doc.getElementsByTagName("staff").item(0);

		// update staff attribute
		NamedNodeMap attr = staff.getAttributes();
		Node nodeAttr = attr.getNamedItem("id");
		nodeAttr.setTextContent("2");

		// append a new node to staff
		Element age = doc.createElement("age");
		age.appendChild(doc.createTextNode("28"));
		staff.appendChild(age);

		// loop the staff child node
		NodeList list = staff.getChildNodes();

		for (int i = 0; i < list.getLength(); i++) {
			
                   Node node = list.item(i);

		   // get the salary element, and update the value
		   if ("salary".equals(node.getNodeName())) {
			node.setTextContent("2000000");
		   }

                   //remove firstname
		   if ("firstname".equals(node.getNodeName())) {
			staff.removeChild(node);
		   }

		}

		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(filepath));
		transformer.transform(source, result);

		System.out.println("Done");

	   } catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	   } catch (TransformerException tfe) {
		tfe.printStackTrace();
	   } catch (IOException ioe) {
		ioe.printStackTrace();
	   } catch (SAXException sae) {
		sae.printStackTrace();
	   }
	}
}

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Prasad G
Guest
Prasad G

I am getting Null doc at
Document doc = docBuilder.parse(filepath);

naveen
Guest
naveen

how to delete attribute

randheer reddy
Guest
randheer reddy

Node importedTemplateChildNode = targetDoc.importNode(templateChildNode, true);
// Importing template node to the target document(this solves wrong_DOCUMENT_ERR:)

targetParentNode.replaceChild(importedTemplateChildNode, targetChildnode);
// Replace target child node with the template node

Transformer tranFac =TransformerFactory.newInstance().newTransformer();
tranFac.transform(new DOMSource(targetDoc), new StreamResult(new FileWriter(targetXmlFile)));

Anuj Prasher
Guest
Anuj Prasher

How can i change the name of the element such as “lastname” to “LNAME”

Naama
Guest
Naama

excellent and accurate explanation. thanks!

ashish
Guest
ashish

I looking for this output with help of java code how can i do it

Raghav
Guest
Raghav

Thanks for this. Its really good.

chithaluri kiran
Guest
chithaluri kiran

Hello Yong,

Thanks for the nice explanation. I would to get the newly generated in a formatted way. Is there any method available to do that. Currently the output xml file is showing everything in one line.

Is there any way to add comments in the newly generated xml files? if yes, Could you please post some code snippets for that.

Thanks in advance.

nithya
Guest
nithya

Hi. thanks for your help. When i update the value of tags i can print in console but the values doesn’t change in the xml file. can u help me pls. it is already asked but i cannot view the solution. where can i get the solution?

Pramod
Guest
Pramod

Hi ,

1 doubt, which is faster , replacing the node or updating ?

João Luís
Guest
João Luís

Hi.
it’s not the first time that your explanations helped me.
Just want to thank you … very much.
Cheers from Portugal
:-)

Anukul
Guest
Anukul

is it possible to add new attribute at particular position or line number……..

Puja
Guest
Puja

Hi MK,

I am trying to update XML file which is present in WEB_INF/Classes/ folder of web application. getting below exception while trying to transform XML, My application is deployed in web sphere.

The same code is working fine on local (Tomcat server)but when i deploy on websphere it gives me (Permission denied) Error

What can i do to resolve this error ?

Rudy
Guest
Rudy

Use jingalo to read data

sherwan hawery
Guest
sherwan hawery

Thank you very much it was very helpful for me………………………………………

trackback
Java: modify XML file (extended) | Moishe Beshkin

[…] dynamically inner xml content. Here is a pretty wonderful solution for simple xml data updating How To Modify XML File In Java – (DOM Parser). I added a mechanism to determine dynamically added xml […]

Joanna
Guest
Joanna

Oops, half of the comment is obviously missing :)

Below is the output I get with your code. Can you explain why the element is misplaced and why there’s this empty line? Thanks.

Joanna
Guest
Joanna

mook kim
mkyong
2000000
28

Gossi
Guest
Gossi

Hi,

I have a question.
I used the Code in this tutorial in my Testingproject:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, “xml”);
transformer.setOutputProperty(OutputKeys.ENCODING, “ISO-8859-1”);
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(xml);
transformer.transform(source, result);

This works fine, but the output in my xml-file istn that good:

blub

jhdfkf

How can i do it, that the second “tagattr” would be formatted as the first one?
When I add a second line in this code (the first was added with an editor), the second line looks like the following:

blub

jhdfkfabcd

Anyone knows what to do?

Gossi
Guest
Gossi

Sorry, the xml wasnt postet right:

blub

jhdfkf

blub

jhdfkfabcdef

trackback
find and replace on large kml files which contain html efficiently? | BlogoSfera
trackback
find and replace on large kml files which contain html efficiently? - QueryPost.com | QueryPost.com
Ratna
Guest
Ratna
Hi Mkyong, I have given the pathname which uses spaces in between, while reading the XML it is fine but when i am trying to write it (transformer.transform(source,result)) it is giving exception path not found. While i tried writing in other directory not having any spaces,it works fine. Can you please suggest how to overcome this problem? String filePath = D:\svn\QTP_Enhancer\CSE Workspace\scrip.xml; try { filepath = URLDecoder.decode(filepath, “UTF-8”); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } Document doc = builder.parse(filePath); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File(filepath)); transformer.transform(source, result);… Read more »
aditya
Guest
aditya

please use instead of “\” use “/” in the file path

Mariano
Guest
Mariano

and dont forget to use “D:/svn/QTP_Enhancer/CSE20%Workspace/scrip.xml “

Ratna
Guest
Ratna

Hello Buddy,

I am facing issue while decoding the document object. Please suggest some way to decode the document onject if file path has space.

chZek
Guest
chZek

This helped me a lot. Thank you so much!

Hawaz
Guest
Hawaz

Thank you !

zyzyjun
Guest
zyzyjun

error occur in Android.
cause DocumentBuilder and Transformer use diff path.

line : Document doc = docBuilder.parse(filepath);
erro : java.net.MalformedURLException: Protocol not found: /data/zyzyjun.xml
resolve: add prefix like “file:///data/xx.xml”

line: transformer.transform(source, result);
erro : not found file
resolve: del prefix like “/data/xx.xml”

Vivek Agrawal
Guest
Vivek Agrawal

This is one of the best java tutorial sites available in the internet.
Thanks for posting such a clean code and complete solution as always :-)
Regards

bck patchouka
Guest
bck patchouka

hi for all , how can read and write on local xml file with android (res/xml/modele.xml)!!
help please , any idea :)
thkxs for all

Andrew Ryan
Guest
Andrew Ryan

You cannot write files stored in the res folder from within your app. You will have to save the file to external storage to be able to edit it

Marte
Guest
Marte

Hi,

I really find your post very helpful. But I have one question, with this code, can you continually modify the XML file? Because in my case, I can only successfully modify the file once..like it really reflects on the xml file. The rest of my trials, it only gets modified at runtime. :( any thoughts?

Toto
Guest
Toto

Dude thanks a lot ! I read all your tutorials on XML/Java, they were great help for me… keep up the great work :) thanks again

Satheesh Kumar
Guest
Satheesh Kumar