首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用XPath设置空值?

如何使用XPath设置空值?
EN

Stack Overflow用户
提问于 2010-04-29 10:55:32
回答 1查看 3.8K关注 0票数 2

使用此xml示例:

代码语言:javascript
复制
<templateitem itemid="5">
   <templateitemdata>%ARN%</templateitemdata>
</templateitem>
<templateitem itemid="6">
   <templateitemdata></templateitemdata>
</templateitem>

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

代码语言:javascript
复制
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值,因为它是空的。但是我使用的代码不能得到节点,因为它是空的。结果为null。

您知道如何获得节点以便我可以设置值吗?

EN

回答 1

Stack Overflow用户

发布于 2010-04-29 13:41:14

我改变了方法,因为:

代码语言:javascript
复制
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);
}

查询://templateitemdata@itemid=6/templateitemdata

以及setValue方法用于:

代码语言:javascript
复制
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()。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2736687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档