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();
	   }
	}
}
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: Blue Coaster33()

  • Pingback: Java: modify XML file (extended) | Moishe Beshkin()

  • 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

      Sorry, the xml wasnt postet right:

      blub

      jhdfkf

      blub

      jhdfkfabcdef

  • Pingback: find and replace on large kml files which contain html efficiently? | BlogoSfera()

  • Pingback: find and replace on large kml files which contain html efficiently? - QueryPost.com | QueryPost.com()

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

    getting exception like could not find the path D:\svn\QTP_Enhancer\CSE20%Workspace\scrip.xml

    at line transformer.transform(source, result); becouse
    document object has captured path as D:\svn\QTP_Enhancer\CSE20%Workspace\scrip.xml

    • aditya

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

  • 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

    This helped me a lot. Thank you so much!

  • Hawaz

    Thank you !

  • 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

    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

    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

    • http://anryan.com 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

    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

    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
  • 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.

  • Portekoi

    Thank’s a lot :)

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

  • Pingback: Hpmework 3 | WWW Technologies Blog()

  • Pingback: (Java) Mengedit File XML (DOM Parse) « Mr.Root()

  • 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

  • http://shkeelstha.blogspot.com 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?

  • 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 –

     &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    		&lt;soap:env xmlns:soapenv=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot; &gt;
    			&lt;soapenv:Body&gt;
    				&lt;serviceResponse&gt;
    					&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
    					&lt;data&gt;
    						&lt;respCode&gt;0&lt;/respCode&gt;
    					&lt;/data&gt;
    				&lt;/serviceResponse&gt;
    			&lt;/soapenv:Body&gt;
    		&lt;/soap:env&gt;
  • 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.

    • http://www.mkyong.com mkyong

      can you post your code and xml file content, so that i can do some testing on it?

      • satish kumar

        Thanks i resolved the issue ,still am not sure what was the root cause for it. What i did is “wrote” the value in another node (parentnode of the one i was trying) and then i could perform my desired task. Does that make any sense to you ? do still need to paste the code.(although) i have changed the code.

      • Kundan Kumar

        Hi i need to create below xml file in java using DOM. I am unable to create this file
        and it’s very urgent. Please help me.

        IGP

        IGP-100
        aaaaaaaaaa

        IGP-200
        bbbbbbbbbb

  • 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

  • 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..

  • 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.

  • 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

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

  • 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….

  • pratap

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

    file.xml

     
    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt;
    &lt;SideBar&gt;
    &lt;Box&gt;party&lt;/Box&gt;
    &lt;Box&gt;Corporate&lt;/Box&gt;
    &lt;party&gt;BirthdayParty&lt;/party&gt;
    &lt;party&gt;TheamParty&lt;/party&gt;
    &lt;Corporate&gt;c1&lt;/Corporate&gt;
    &lt;Corporate&gt;c2&lt;/Corporate&gt;
    &lt;/SideBar&gt;

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

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

  • sithu

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

  • 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

  • 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.

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

  • Amresh kumar chaudhary

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

    • http://www.mkyong.com mkyong

      Convert XML code to Java code!? Sorry, don’t get you, please elaborate in detail.

    • Life Saviour

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

  • http://djstools.com/cerca/italia italia

    Hi, this is a good post!

  • Guru Prasad

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

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

  • Pingback: Java XML Tutorial()