Java Reference
In-Depth Information
//we're throwing any exception out
updateValueInXmlFile(xmlSource, xmlSource, xpath, value);
out.println("All done.");
}
public static void updateValueInXmlFile(String fileIn,
String fileOut, String xpathExpression,
String newValue) throws IOException {
// Set up the DOM evaluator
final DocumentBuilderFactory docFactory =
DocumentBuilderFactory.newInstance();
try {
final DocumentBuilder docBuilder =
docFactory.newDocumentBuilder();
final Document doc = docBuilder.parse(fileIn);
final XPath xpath =
XPathFactory.newInstance().newXPath();
NodeList nodes =
(NodeList) xpath.evaluate(xpathExpression,
doc, XPathConstants.NODESET);
// Update the nodes we found
for (int i = 0, len = nodes.getLength(); i < len; i++) {
Node node = nodes.item(i);
node.setTextContent(newValue);
}
// Get file ready to write
final Transformer transformer =
TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT,
"yes");
transformer.setOutputProperty(OutputKeys.ENCODING,
"UTF-8");
StreamResult result =
new StreamResult(new FileWriter(fileOut));
transformer.transform(new DOMSource(doc), result);
// Write file out
result.getWriter().flush();
Search WWH ::




Custom Search