使用这个 xml 示例:
<templateitem itemid="5">
<templateitemdata>%ARN%</templateitemdata>
</templateitem>
<templateitem itemid="6">
<templateitemdata></templateitemdata>
</templateitem>
我正在使用 XPath 获取和设置节点值。我用来获取节点的代码是:
private static Node ***getNode***(Document doc, String XPathQuery) throws XPathExpressionException
{
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile(XPathQuery);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
if(nodes != null && nodes.getLength() >0)
return nodes.item(0);
throw new XPathExpressionException("No node list found for " + XPathQuery);
}
获取 %ARN% 值:“//templateitem[@itemid=5]/templateitemdata/text()”并使用 getNode 方法我可以获得节点,然后调用getNodeValue()。
除了获取该值外,我还想为“templateitem[@itemid=6]”设置 templateitemdata 值,因为它是空的。但是我使用的代码无法获取节点,因为它是空的。 result 为空。
您知道获取节点以便我设置值的方法吗?
最佳答案
您只需请求元素节点本身(而不是它的子文本节点):
//templateitem[@itemid=6]/templateitemdata
getNodeValue()
也适用于元素节点,在这两种情况下,在 XPath 中使用 text()
是完全多余的。
关于java - 如何使用 XPath 设置空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2736687/