Originally posted by Nick Heppleston at: http://www.modhul.com/2009/01/20/selecting-unknown-nodes-in-xpath/
My currrent project can invoke several common web-services that return roughly the same data, but with slightly different sub elements. I have just had a requirement to count the number of these slightly differing elements using a common XPath statement and I’m amazed by how simple it is, so I thought I would share my findings here.
Consider the following example web-service responses (note the common failure element, but different sub-elements):
<WebServiceResponse> <Failed> <FailedValue>Value1</FailedValue> <FailedValue>Value2</FailedValue> <FailedValue>Value3</FailedValue> </Failed> </WebServiceResponse>
<WebServiceResponse> <Failed> <CompletelyDifferentFailedValue>Value1</CompletelyDifferentFailedValue> <CompletelyDifferentFailedValue>Value2</CompletelyDifferentFailedValue> </Failed> </WebServiceResponse>
To determine the number of possible child elements underneath the Failed element with a common XPath statement, we can use one of several wildcards:
- * – selects any element node
- @* – selects any attribute node
- node() – selects any node (irrespective of type)
In our case, we always want to count element nodes, so our XPath becomes:
which returns a value of ’3′ and ’2′ from the examples above.