/**
* 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);
}
}
Saturday, April 11, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment