This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes I/O and Streams and the fly likes Update Xml file-Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Update Xml file-Java" Watch "Update Xml file-Java" New topic

Update Xml file-Java

Chaithika Prabudda

Joined: Apr 11, 2009
Posts: 2
* This code is used to update a xml file.
* Update only a value in a given tag
* constructor takes file path, tag name which has to be modify and the new value which
* should write to the particular tag
package softdiary;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

* @author chaithika
public class SoftDiaryXmlLineWriter{

SoftDiaryXmlLineWriter(String xmlFilePath,String tagename,String newValue) {
//constructor takes followings
//get the path where file exist, tag name which contain value where we want to update and new value to insert in to that particular tag
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlFilePath);

replaceValue(doc, tagename, newValue);

Transformer t = TransformerFactory.newInstance().newTransformer();
Result result = new StreamResult(new File(xmlFilePath));
Source source = new DOMSource(doc);
t.transform(source, result);
catch(Exception e){



private static void replaceValue(Document doc, String tagName, String replaceValue) {
NodeList nodeList = doc.getElementsByTagName(tagName);
Node node = nodeList.item(0);
Rob Spoor

Joined: Oct 27, 2005
Posts: 19655

Please Use Code Tags.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Update Xml file-Java
Similar Threads
code to read the xml and also overide the value of certain attributes in xml at runtime itself
problem in modification of the value in xml file
Getting the arraylist through session
xml JAVA
problem in deleting the file