Two Laptop Bag*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Update Xml file-Java" Watch "Update Xml file-Java" New topic
Author

Update Xml file-Java

Chaithika Prabudda
Greenhorn

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 java.io.File;
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 javax.xml.transform.stream.StreamResult;
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) {
try{
//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);
node.getFirstChild().setNodeValue(replaceValue);
}
}
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

Please Use Code Tags.


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