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. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
55 Comment threads
16 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
54 Comment authors
SandileBibhu PandeyHimanshi NeekhraPrasad Gnaveen Recent comment authors
newest oldest most voted
Prasad G
Guest
Prasad G

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

Anuj Prasher
Guest
Anuj Prasher

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

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 […]

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

trackback
Java XML Tutorial

[…] which contains a lot of data.Read a XML file Read a XML file and print it out each elements.Modify existing XML file Modify an existing XML file, by update the element and attribute, and also how to delete a […]

Guru Prasad
Guest
Guru Prasad

can u please send me code to set password value as RAMRAJ

<agentlist ip="10.10.0.1" user="abc" password="1234567"

italia
Guest
italia

Hi, this is a good post!

Amresh kumar chaudhary
Guest
Amresh kumar chaudhary

please tell me how to convert this xml code to java code
thank u

Life Saviour
Guest
Life Saviour

Its already implemented in java. Like mkyong stated elaborate on your question.

Julius
Guest
Julius

Hi! great job! Please, tell us how to compare two different xml files? Can I organize two throws for reading two xml files in the same time?

Naveen
Guest
Naveen

THANKS IN ADVANCE…YOUR CODE IS HELPING ME TO A VERY GREAT EXTENT SO WANNA THANK YOU FOR THIS AGAIN…!

CAN YOU PLEASE GIVE ME A CODE TO DELETE A PARENT TAG USING A CHILD TAG…FOR A BETTER UNDERSTANDING I AM LEAVING WITH AN EXAMPLE BELOW!

Now using child1 tag ,i have to delete the parent tag ..can you please please please help me in doing this.

ROHIT AHUJA
Guest
ROHIT AHUJA

sir,thank you for helping by your code ,i want to add 1 in an attribute in an xml file
please help me and make the changes to an xml file in that particular attribute

sithu
Guest
sithu

Sir,
The above code will work only for file.xml right?
How to modify a random xml file?

pratap
Guest
pratap

Hie, That was awesome code…
Can you help me in xml modification plz.

file.xml


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SideBar>
<Box>party</Box>
<Box>Corporate</Box>
<party>BirthdayParty</party>
<party>TheamParty</party>
<Corporate>c1</Corporate>
<Corporate>c2</Corporate>
</SideBar>

here I wand to delete BirthdayParty tag ie:- BirthdayParty
How it can be done…!

pratap
Guest
pratap

Got it:
Node sb = doc.getElementsByTagName(“SideBar”).item(0);

Element SideBar = doc.getDocumentElement();
NodeList Box = SideBar.getElementsByTagName(BoxName);

for (int j=0; j<Box.getLength(); j++ )
{
Node BoxItem = Box.item(j);
if ( isTextNode(BoxItem))
continue;
String strBoxName=BoxItem.getTextContent();
if(strBoxName.equals(PageName))
{
sb.removeChild(BoxItem);
}
}

Raj
Guest
Raj

hi sir,how can I update integer value in xml through Java? I want to do arithmetic operation and update XML childnode’s value through java….

kennha811
Guest
kennha811

NodeList nodelist1=nodestudent1.getChildNodes();
for(int i=0;i<nodelist1.getLength();i++)
{
Node node=nodelist1.item(i);
if(node.getNodeName().equals("party"))
{
//node.getNodeValue();
if(node.getTextContent().equals("BirthdayParty"))
{
nodestudent1.removeChild(node);
}
}
}

pratap
Guest
pratap

Your method is much simpler and efficient…
I will implement it…:)

Arvind
Guest
Arvind

Dear Sir,

I want to save the modified XML into a String variable- you have showed how to save it to a file.

Please let me know how to save the modified XML to a string variable.

Thanks,
Arvind.

kishore
Guest
kishore

TransformerFactory transformerFac = TransformerFactory.newInstance();
Transformer transformer = transformerFac.newTransformer();
StreamResult streamResultToResp = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, streamResultToResp);
//Now assing to string variable
String xmlVal = streamResultToResp.getWriter().toString();

kishore
Guest
kishore

Here, doc is the your updated document.

tanisha
Guest
tanisha

my saved xml is==>

21
techno
mumbai

46
management
lucknow

52
banking
varanasi

15
student
ahemdabad

i want to xtend my xml like this==>

21
techno
mumbai

46
management
lucknow

52
banking
varanasi

15
student
ahemdabad

25
technical
delhi

44
management
lucknow

42
private
gujrat

15
kid
allahabad

using dom parser …plz help..

tanisha
Guest
tanisha

21
techno
mumbai

46
management
lucknow

52
banking
varanasi

15
student
ahemdabad

25
technical
delhi

44
management
lucknow

42
private
gujrat

15
kid
allahabad

satish kumar
Guest
satish kumar

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?\

Thanks for the awesome code BTW.

Yogesh Patil
Guest
Yogesh Patil

can you help me in parsing xml with nested tags. when i am trying to parse this xml, i m getting parsing error.
XML –

 <?xml version="1.0" encoding="utf-8"?>
		<soap:env xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" >
			<soapenv:Body>
				<serviceResponse>
					<?xml version="1.0" encoding="UTF-8"?>
					<data>
						<respCode>0</respCode>
					</data>
				</serviceResponse>
			</soapenv:Body>
		</soap:env> 
Shakeel Shrestha
Guest
Shakeel Shrestha

Hi mkyong,

Instead of passing xml file path to parse method, I have to pass the content of xml as string. How can I do it?

Shakeel Shrestha
Guest
Shakeel Shrestha
jiji
Guest
jiji

it a good example for tutorial but i what if i want to use the DOM parsing in android this will workk ???? plz reply help

trackback
(Java) Mengedit File XML (DOM Parse) « Mr.Root

[…] : http://www.mkyong.com/java/how-to-modify-xml-file-in-java-dom-parser/ Share this:TwitterFacebookLike this:LikeBe the first to like this. […]

trackback
Hpmework 3 | WWW Technologies Blog
ivan
Guest
ivan

Hi Mkyong

for this line below : when i try to Sysout , why the code rewrite my xml file not update the value what i want. Please advice or example ?

thanks

// 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, System.out);

Portekoi
Guest
Portekoi

Thank’s a lot 🙂

Satheesh Kumar
Guest
Satheesh Kumar

The thing i am not clear that how to handle the following xml scenario:

yong
mook kim
mkyong

1000
150

sanjay
machani
chong

2000
200


My staff tag won’t be having id and also i would be having child tags for salary. But i need to change salary for sanjay(firstname) in xml using java.

Satheesh Kumar
Guest
Satheesh Kumar
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

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?