Selecting Unknown Nodes in XPath

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>

and:

<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:

count(//WebServiceResponse/Failed/*)

which returns a value of ‘3’ and ‘2’ from the examples above.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s