使用 XPath Java 设置节点值 [英] Setting node value using XPath Java

查看:20
本文介绍了使用 XPath Java 设置节点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 XPath 设置节点值.我有以下内容,但它似乎没有改变实际的文件值.

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?

谢谢

推荐答案

您只是在更改内存中的值,而不是文件本身.您需要将修改后的文档写回到文件中:

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
}

这些类都来自javax.xml.transform.*.

(当然,您需要保存对文档的引用,以便您可以写回它(即,您将无法继续将其直接传递给 evaluate)).

(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)).

这篇关于使用 XPath Java 设置节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆