使用XPath Java设置节点值

时间:2011-12-20 22:59:30

标签: java xpath xmlnode

我正在尝试通过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
}

但该节点的文件内容保持不变。

如何设置该节点的值?

由于

1 个答案:

答案 0 :(得分:2)

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

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))。< / p>