Home > Java > Modifying / Editing XML Document in JAVA

Modifying / Editing XML Document in JAVA

Unlike PHP, C# or Asp.Net working with XML in Java is very big headache. I spend more than a day on Google searching for modifying an xml document in java. Finally i managed to get bits and pieces code snippets from various site and This article will guide you how we can modify the xml document in java, servlet and JSP.

This code snippets presented here does not uses third party XML Parser.

The structure of the XML document getting used here are:

< ?xml version="1.0" encoding="UTF-8"?>
     <connection>
	<number id="1"/>	
	<number id="2"/>	
     </connection>

XML Parser Package getting imported:

	import org.w3c.dom.*;
	import javax.xml.parsers.*; 
	import javax.xml.transform.*; 
	import javax.xml.transform.dom.DOMSource; 
	import javax.xml.transform.stream.StreamResult; 
	import org.xml.sax.SAXException;

Loading and Parsing XML Document:

	File file = new File("connections.xml");
 
	//Create instance of DocumentBuilderFactory
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 
	//Get the DocumentBuilder
	DocumentBuilder docBuilder = factory.newDocumentBuilder();
 
	//Parsing XML Document
	Document doc = docBuilder.parse(file);

Getting XML Root Element:

	Element root = doc.getDocumentElement();

Creating child Node:

	//Pointing to document root element
	Element root = doc.getDocumentElement();
 
	//create child element having tagName=number
	Element childElement = doc.createElement("number");
 
	//Adding number tag to root element
	root.appendChild(childElement);

Adding Attributes to an Element:

 
	//Pointing to document root element
	Element root = doc.getDocumentElement();
 
	//create child element having tagName=number
	Element childElement = doc.createElement("number");
 
	//Add the attribute to the child
	childElement.setAttribute("id","3");
 
	//Adding number tag havind id attribute to root element
	root.appendChild(childElement);

Your email:

 


Saving the modified xml file:

    //setting up a transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
 
    //generating string from xml tree
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(doc);
    trans.transform(source, result);
    String xmlString = sw.toString();
 
    //Saving the XML content to File
    OutputStream f0;
    byte buf[] = xmlString.getBytes();
    f0 = new FileOutputStream("connections.xml");
    for(int i=0;i<buf .length;i++) {
 	f0.write(buf[i]);
    }
	f0.close();
	buf = null;

Java Code for Modifying/Editing XML File:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.io.OutputStream;
import java.io.StringWriter;
import org.w3c.dom.*;
import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 
import org.xml.sax.SAXException;
 
public class modifyXML {
   public static void main(String args[]) {
     try {	
	File file = new File("connections.xml");
 
	//Create instance of DocumentBuilderFactory
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 
	//Get the DocumentBuilder
	DocumentBuilder docBuilder = factory.newDocumentBuilder();
 
	//Using existing XML Document
	Document doc = docBuilder.parse(file);
 
	//create the root element
	Element root = doc.getDocumentElement();
 
	//create child element
	Element childElement = doc.createElement("number");
 
        //Add the attribute to the child
	childElement.setAttribute("id","3");
	root.appendChild(childElement);
 
	//set up a transformer
	TransformerFactory transfac = TransformerFactory.newInstance();
	Transformer trans = transfac.newTransformer();
 
        //create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        String xmlString = sw.toString();
 
        OutputStream f0;
	byte buf[] = xmlString.getBytes();
	f0 = new FileOutputStream("connections.xml");
	for(int i=0;i<buf .length;i++) {
	   f0.write(buf[i]);
	}
	f0.close();
	buf = null;
     }
     catch(SAXException e) {
	e.printStackTrace();		
     }
     catch(IOException e) {
        e.printStackTrace();		
     }
     catch(ParserConfigurationException e) {
       e.printStackTrace();		
     }
     catch(TransformerConfigurationException e) {
       e.printStackTrace();		
     }
     catch(TransformerException e) {
       e.printStackTrace();		
     }
  }
}


Custom Search

Popular Articles:

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • IndianPad
  • LinkedIn
  • Live
  • MySpace
  • Netvibes
  • RSS
  • Technorati
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • Reddit
  • Add to favorites
  • PDF
  • Twitter
Categories: Java Tags: ,
  1. Ragavendra
    November 28th, 2008 at 02:38 | #1

    How to edit a XML child node value?

  2. Croyte
    February 27th, 2009 at 23:03 | #2

    Ragavendra, please appreciate what this guy has done. You didnt even thank him and rather just asked a question. Where are your manners ? This this the way you were taught to behave ? Now stop asking stupid question and thank him.

  3. madhavi
    March 16th, 2009 at 00:24 | #3

    How to edit a XML child node value?
    please give me the code.
    Thanks in advance.

  4. Michael Fons
    May 18th, 2009 at 14:54 | #4

    Croyte, your comment is very funny!! Hitesh Agrawal, THANK YOU VERY MUCH for sharing this valuable lesson you had to dig for. It is very useful to me.

    And, Croyte: I was going to thank him anyway before I read your comment.

  5. Mohit
    June 9th, 2009 at 00:13 | #5

    Thanks a lot. You Rock

  6. Jeevananth
    June 14th, 2009 at 09:13 | #6

    Its really very description and code.Good . Keep working.

  7. calyp
    August 14th, 2009 at 01:54 | #7

    hi there it was a well written piece of codes.
    however i am wondering is it possible to edit a existing child element.
    as in search through the xml files and edit the corresponding child element.

    any help will be greatly appreciated.

  8. August 21st, 2009 at 12:07 | #8

    You can use vtd-xml to accomplish editing and modification with huge efficiency improvement
    http://vtd-xml.sf.net

  9. mido
    October 9th, 2009 at 13:03 | #9

    thaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaanks :d

  10. Raghav
    November 8th, 2009 at 22:12 | #10

    thanks…………………

  11. Sandeep
    January 3rd, 2010 at 14:38 | #11

    Thanks for this excellent tutorial. Couple of additional lines to make xml file indented
    trans.setOutputProperty(OutputKeys.INDENT, “yes”);
    trans.setOutputProperty(“{http://xml.apache.org/xslt}indent-amount”, “4″);

  12. Aditya Andhalikar
    January 5th, 2010 at 13:44 | #12

    Thanks a lot

  13. Vakul Agarwal
    February 3rd, 2010 at 03:58 | #13

    Much Appreciated!!

    All required syntactics neatly placed and explained.

    Saved a lot of effort.

    Thanks Hitesh…

    Looking forward for more.

  14. March 11th, 2010 at 21:01 | #14

    thanks a lot
    it helps me very much

  15. Zenith
    May 4th, 2010 at 10:02 | #15

    Nice! Great summary. It helps me a lot!!

  16. Youness
    May 14th, 2010 at 22:31 | #16

    Thanks so much…

  17. Vitaliy
    May 19th, 2010 at 07:29 | #17

    Thanks for solution!! This is the best one!
    I looking for such simple and clear desision.

  18. Dominik
    June 14th, 2010 at 07:01 | #18

    Thanx!

    I’ve got a question: How can you delete a node from an existing XML????

  19. Priya Mittal
    June 18th, 2010 at 05:23 | #19

    Thanks. It worked.

  20. Ashley
    September 2nd, 2010 at 22:24 | #20

    Hey Thanks a Heaps…….

    Its very useful…..

  1. No trackbacks yet.