如何使用XPath设置空值?

时间:2010-04-29 10:55:32

标签: java xml xpath

使用这个xml示例:

<templateitem itemid="5">
   <templateitemdata>%ARN%</templateitemdata>
</templateitem>
<templateitem itemid="6">
   <templateitemdata></templateitemdata>
</templateitem>

我使用XPath来获取和设置Node值。我用来获取节点的代码是:

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值,因为它为空。但是我使用的代码无法获取节点,因为它是空的。 结果 为空。

您知道获取节点的方法,以便我可以设置值吗?

2 个答案:

答案 0 :(得分:2)

您只需要询问元素节点本身(而不是其子文本节点):

//templateitem[@itemid=6]/templateitemdata

getNodeValue()也适用于元素节点,在两种情况下,在XPath中使用text()完全是多余的。

答案 1 :(得分:0)

我改变了方法:

public 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.NODE);
    Node node = (Node) result;
    if(node != null )
        return node;
    throw new XPathExpressionException("No node list found for " + XPathQuery);
}

查询:// templateitem [@ itemid = 6] / templateitemdata

和setValue方法:

public static void setValue(final Document doc, final String XPathQuery, final String value) throws XPathExpressionException
{
    Node node = getNode(doc, XPathQuery);
     if(node!= null)
             node.setTextContent(value);
     else
         throw new XPathExpressionException("No node found for " + XPathQuery);
}

我使用setTextContent()而不是setNodeValue()。