This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Update Xml file-Java

 
Chaithika Prabudda
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
/**
* 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
Pie
Posts: 20496
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please Use Code Tags.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic