使用 XPath Java 设置节点值
我正在尝试通过 XPath 设置节点值。我有以下内容,但它似乎没有改变实际文件值。
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
}
但该节点的文件内容保持不变。
如何设置该节点的值?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只是更改内存中的值,而不是文件本身的值。您需要将修改后的文档写回到文件中:
这些类都来自
javax.xml.transform.*
。(当然,您需要保存对文档的引用,以便可以写回它(即您将无法继续将其直接传递到
evaluate
))。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:
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
)).