Patrick Marty
Patrick Marty

Reputation: 487

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 ?

Upvotes: 5

Views: 4092

Answers (3)

Michael Kay
Michael Kay

Reputation: 163625

Just for completeness, in XSLT 2.0 you can do

<xsl:if test="self::attribute()">...</xsl:if>

Upvotes: 2

Tomalak
Tomalak

Reputation: 338406

A few things to understand:

  1. . refers to the current node (aka "context node")
  2. an attribute node has a parent (the element it belongs to)
  3. an XPath union operation (with |) never duplicates nodes, i.e. (.|.) results in one node, not two
  4. there is the self:: axis you could use in theory (e.g. self::* works to find out if a node is an element), but self::@* 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(.|../@*) equals count(../@*), the current node must be an attribute node.

Upvotes: 7

cordsen
cordsen

Reputation: 1701

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

Upvotes: 1

Related Questions