简体   繁体   中英

Setting node value using XPath Java

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

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 (ie you won't be able to continue passing it directly into evaluate )).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM