XPath test to identify node type
I don't understand why this test
count(.|../@*)=count(../@*)
开发者_开发知识库( from Dave Pawson's Home page )
identify an attribute node :(
could someone give me a detailled explanation ?
A few things to understand:
.
refers to the current node (aka "context node")- an attribute node has a parent (the element it belongs to)
- an XPath union operation (with
|
) never duplicates nodes, i.e.(.|.)
results in one node, not two - there is the
self::
axis you could use in theory (e.g.self::*
works to find out if a node is an element), butself::@*
does not work, so we must use something different
Knowing that, you can say:
../@*
fetches all attributes of the current node's parent (all "sibling attributes", if you will)(.|../@*)
unions the current node with them – if the current node is an attribute, the overall count does not change (as per #3 above)- therefore, if
count(.|../@*)
equalscount(../@*)
, the current node must be an attribute node.
Just for completeness, in XSLT 2.0 you can do
<xsl:if test="self::attribute()">...</xsl:if>
Here is how this works
count( # Count the nodes in this set
.|../@*) # include self and all attributes of the parent
# this counts all of the distinct nodes returned by the expression
# if the current node is an attribute, then it returns the count of all the
# attributes on the parent element because it does not count the current
# node twice. If it is another type of node it will return 1 because only
# elements have attribute children
=count( # count all the nodes in this set
../@*) # include all attribute nodes of the parent. If the current node is not an
# attribute node this returns 0 because the parent can't have attribute
# children
精彩评论