【问题标题】:pugixml: find out whether xpath matches a particular node/attributepugixml:找出 xpath 是否匹配特定节点/属性
【发布时间】:2012-08-16 15:40:05
【问题描述】:

给定一个xpath_query 和一个xml_attribute 或xml_node,我想知道查询是否会匹配该属性或节点。

我可以将查询评估为xpath_node_set,然后检查节点是否在内部,如下所示:

bool match(const pugi::xpath_query& query, const pugi::xml_node& node)
{
    for (const auto& child : query.evaluate_node_set(node.parent()))
    {
        if (child.node() == node)
            return true;
    }
    return false;
}

但是,这似乎有点贵。有没有更便宜的方法?

【问题讨论】:

    标签: c++ xpath pugixml


    【解决方案1】:

    使用:

     count(expressionSelectingTheNode | theQuery) = count(theQuery)
    

    您需要用正确的表达式替换上面的“expressionSelectingTheNode”和“theQuery”。

    当且仅当表达式 expressionSelectingTheNode 选择的单个节点是表达式 theQuery 选择的节点之一时,才会返回 true()。

    示例:

    如果我们有这个 XML 文档:

    <nums>
      <num>01</num>
      <num>02</num>
      <num>03</num>
      <num>04</num>
      <num>05</num>
      <num>06</num>
      <num>07</num>
      <num>08</num>
      <num>09</num>
      <num>10</num>
    </nums>
    

    而节点为(被/*/num[. = 6]选中):

      <num>06</num>
    

    表达式为(选择所有值既是 2 的倍数又是 3 的倍数的 num 元素):

    /*/num[. mod 2 = 0 and . mod 3 = 0]  
    

    然后我们评估这个表达式:

       count(/*/num[. = 6] | /*/num[. mod 2 = 0 and . mod 3 = 0])
      =
       count(//*/num[. mod 2 = 0 and . mod 3 = 0])
    

    结果是true()。

    如果我们评估这个表达式(想看看&lt;num&gt;05&lt;/num&gt;是否也被选中):

       count(/*/num[. = 5] | /*/num[. mod 2 = 0 and . mod 3 = 0])
      =
       count(//*/num[. mod 2 = 0 and . mod 3 = 0])
    

    结果现在是false()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 2012-12-23
      • 2018-01-09
      • 1970-01-01
      • 2015-07-09
      • 2021-08-16
      相关资源
      最近更新 更多