How to modify XML file in Java

Posted: February 28, 2012 in Java Posts
Tags: , , , , ,

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

	yong
	mook kim
	mkyong
	100000

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.

 

	mook kim
	mkyong
	2000000 
        28

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();
	   }
	}
}
Advertisements
Comments
  1. Lorene Mcwhirt says:

    Simply want to say your article is as surprising. The clearness to your publish is just great and i could think you are knowledgeable in this subject. Fine together with your permission allow me to grasp your feed to keep up to date with drawing close post. Thanks one million and please keep up the gratifying work.

    Like

  2. e-tupakka says:

    I like this web site so much, saved to fav. “Nostalgia isn’t what it used to be.” by Peter De Vries.

    Like

  3. certified nurse assistant says:

    I was suggested this blog via my cousin. I am now not positive whether this publish is written via him as no one else realize such specified approximately my trouble. You are incredible! Thank you!

    Like

  4. teething chart says:

    I was looking at some of your content on this site and I believe this web site is really informative! Keep on putting up.

    Like

  5. Rafaela Dewire says:

    Good blog! I truly love how it is simple on my eyes and the data are well written. I’m wondering how I could be notified when a new post has been made. I’ve subscribed to your feed which must do the trick! Have a great day!

    Like

  6. forex option trading education says:

    The other day, while I was at work, my cousin stole my iPad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views. I know this is totally off topic but I had to share it with someone!

    Like

  7. hybrid car reviews says:

    Wohh precisely what I was searching for, thanks for putting up. “If it’s meant to be it’s up to me.” by Terri Gulick.

    Like

  8. sexchat says:

    I truly appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thank you again!

    Like

  9. cheap vacations says:

    Outstanding share it is really. I have been awaiting for this tips.

    Like

  10. internet music licensing says:

    Thanks for helping out, wonderful information. “The surest way to be deceived is to think oneself cleverer than the others.” by La Rochefoucauld.

    Like

  11. Robert Merril says:

    I would like to thnkx for the efforts you have put in writing this site. I am hoping the same high-grade web site post from you in the upcoming also. Actually your creative writing abilities has inspired me to get my own website now. Actually the blogging is spreading its wings quickly. Your write up is a good example of it.

    Like

  12. san antonio finest restaurants says:

    I’m really enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Fantastic work!

    Like

  13. kore dizileri izle says:

    you’re seriously amount one particular admin your blogging is wonderful i constantly check your webpage i am guaranteed you will be the best

    Like

  14. seoul korea says:

    But a smiling visitant here to share the love (:, btw outstanding pattern .

    Like

  15. pancreatic cancer ribbon clip art says:

    Wow that was unusual. I just wrote an very long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say wonderful blog!

    Like

  16. colleges with nursing programs says:

    You have remarked very interesting details! ps nice web site.

    Like

  17. poptropica help says:

    Would love to forever get updated outstanding website ! .

    Like

  18. eliminating credit card bills says:

    There is visibly a bunch to know about this. I feel you made certain good points in features also.

    Like

  19. Carmelita says:

    Just wanna input on few general things, The website style is perfect, the content material is really great : D.

    Like

  20. daily forex historical data says:

    Thankyou for this marvellous post, I am glad I detected this internet site on yahoo.

    Like

  21. four micro onde says:

    F*ckin’ awesome issues here. I am very happy to peer your article. Thank you so much and i’m looking ahead to touch you. Will you kindly drop me a mail?

    Like

  22. we are fans says:

    stupefaction goombay murdstone Concetta breese veruca husk camembert tot

    Like

  23. Van says:

    You have remarked very interesting details ! ps decent website . “Enemies, as well as lovers, come to resemble each other over a period of time.” by Sydney Harris.

    Like

  24. Site indexer says:

    As soon as I noticed this web site I went on reddit to share some of the love with them.

    Like

  25. Eva Angelina says:

    Thanks for helping out, wonderful information.

    Like

  26. disque dur externe pas cher says:

    I like this post, enjoyed this one regards for putting up.

    Like

  27. roulette games says:

    I genuinely enjoy looking at on this web site , it holds wonderful articles . “Words are, of course, the most powerful drug used by mankind.” by Rudyard Kipling.

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s