首页 文章

XPath:如何选择没有属性的节点?

提问于
浏览
75

使用XPath,如何选择没有属性的节点(其中属性count = 0)?

例如:

<nodes>
    <node attribute1="aaaa"></node>
    <node attribute1="bbbb"></node>
    <node></node> <- FIND THIS
</nodes>

3 回答

  • 123
    //node[not(@*)]
    

    这是在没有任何属性的情况下选择文档中名为“node”的所有节点的XPath .

  • 4
    //node[count(@*)=0]
    

    将选择具有零属性的所有<node>

  • 21

    解决Marek Czaplicki的评论并扩大答案

    //node[not(@*) or not(string-length(@*))]
    

    ....将选择所有具有零属性的节点元素,或者具有全部属性为空的节点元素 . 如果它只是您感兴趣的特定属性,而不是所有属性,那么您可以使用

    //node[not(@attribute1) or not(string-length(@attribute1))]
    

    ...这将选择所有没有名为 attribute1 OR的属性的节点元素,这些属性的 attribute1 属性为空 .

    也就是说,这些xpath表达式中的任何一个都会选择以下元素

    <nodes>
        <node attribute1="aaaa"></node>
        <node attribute1=""></node> <!--This one -->
        <node attribute1="bbbb"></node>
        <node></node> <!--...and this one -->
    </nodes>
    

相关问题