XPath:如何查找仅具有指定属性且没有其他属性的节点

时间:2013-10-06 06:29:10

标签: xml xpath

以下示例说明了我的问题:

<nodes>
   <node at1="1" at2="2"> 12 </node>
   <node at1="1" at2="2" at3="3"> 123 </node>
   <node at1="1"> 1 </node>        <-----find this node
</nodes>

/nodes/node[@at1]返回所有三个节点,但我正在寻找只有“at1”属性且没有其他属性的节点。

1 个答案:

答案 0 :(得分:4)

这会发现node具有属性@at1,而没有其他属性:

//node[@at1 and count(@*) = 1]

如果您想允许其他可选属性x,您可以这样做:

//node[@at1 and count(@*) - count(@x) = 1]

如果您的节点具有xmlns名称空间声明,如下所示:

<nodes>
   <node at1="1"> 1 </node>
   <node at1="2" xmlns="http://xyz"> 2 </node>
</nodes>

您可以像这样匹配两个节点:

//*[name()='node' and @at1 and count(@*) = 1]

仅匹配具有xmlns的节点:

//*[name()='node' and @at1 and count(@*) = 1 and namespace-uri()='http://xyz']

仅匹配没有xmlns的节点:

//*[name()='node' and @at1 and count(@*) = 1 and namespace-uri()='']