-->

Setting node value using XPath Java

2019-07-04 06:12发布

问题:

I'm trying to set a node value via an XPath. I have the following but it doesn't seem to change the actual files value.

XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();

xPathExpression = "//test";
xPathValue= "111";

NodeList nodes = (NodeList) xPath.evaluate(xPathExpression, new InputSource(new FileReader(fileName)), XPathConstants.NODESET);

for (int k = 0; i < nodes.getLength(); i++)
{
    System.out.println(nodes.item(k).getTextContent());  // Prints original value
    nodes.item(k).setTextContent(xPathValue);
    System.out.println(nodes.item(k).getTextContent());  // Prints 111 after
}

But file contents for that node remain unchanged.

How do I set the value of that node?

Thanks

回答1:

You're merely changing the value in memory, not in the file itself. You need to write the modified document back out to the file:

Source source = new DOMSource(doc);
Result result = new StreamResult(new File(fileName));
Transformer xformer;
try {
    xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
    // TODO Auto-generated catch block
} catch (TransformerFactoryConfigurationError e) {
    // TODO Auto-generated catch block
} catch (TransformerException e) {
    // TODO Auto-generated catch block
}

These classes all come from javax.xml.transform.*.

(You'll need to save a reference to the document, of course, so that you can write back to it (i.e. you won't be able to continue passing it directly into evaluate)).