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);
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:
- Ajax Programming with JSP and Servlets
- Reading Microsoft Word Document in JAVA
- JSON in JAVA
- Date Manipulation in JAVA
- Reading IMAP Server Emails Using Java
- Performing Text To Speech (TTS) conversion on linux using Java
- HTTP POST File Content in JAVA
- Log4J Logging Inside Eclipse Console
- Checking Image Resolution from Java Applications
- Understanding Prototype Design Pattern in Java



































How to edit a XML child node value?
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.
How to edit a XML child node value?
please give me the code.
Thanks in advance.
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.
Thanks a lot. You Rock
Its really very description and code.Good . Keep working.
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.
You can use vtd-xml to accomplish editing and modification with huge efficiency improvement
http://vtd-xml.sf.net
thaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaanks :d
thanks…………………
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″);
Thanks a lot
Much Appreciated!!
All required syntactics neatly placed and explained.
Saved a lot of effort.
Thanks Hitesh…
Looking forward for more.
thanks a lot
it helps me very much
Nice! Great summary. It helps me a lot!!
Thanks so much…
Thanks for solution!! This is the best one!
I looking for such simple and clear desision.
Thanx!
I’ve got a question: How can you delete a node from an existing XML????
Thanks. It worked.
Hey Thanks a Heaps…….
Its very useful…..