tags:

views:

21

answers:

2
+1  Q: 

XPath Query Help

<?xml version="1.0" encoding="ISO-8859-1"?>

<users>

<user number="0775547857">
   <step stepnumber="1">complete</step>
   <step stepnumber="2">complete</step>
   <step stepnumber="3">complete</step>
</user>

<user number="0775543754">
   <step stepnumber="1">complete</step>
   <step stepnumber="2">complete</step>
</user>

<user number="0777743059">
   <step stepnumber="1">complete</step>
</user>

</users>

Given a number, I want to find the maximum stepnumber in the list of steps.

What i've got so far is //user[@number='0775547857']/step[@stepnumber]

And i think I have to use the fn:max function but I am having trouble on how to use the max function passing the list of step numbers.

Example : If i give number 0775547857, the maximum step number is 3 and for 0775543754 it is 2 and so on.

Thanx a lot in advance.

Is this correct?

//user[@number='0772243950']/step[fn:max((@stepnumber))]
A: 

Try this: fn:max(//user[@number='0775547857']/step[@stepnumber])

Adam Crume
+1  A: 

The max() function is defined only in XPath 2.0 and above.

An XPath 2.0 expression that finds the maximum stepnumber of the step children of a user that has a number attribute with value $pNum is:

max(/*/user[@number=$pNum]/step/@stepnumber/xs:integer(.))

Substituting $pnum with 0775547857 and evaluating this XPath 2.0 expression on the following XML document:

<users>
    <user number="0775547857">
        <step stepnumber="1">complete</step>
        <step stepnumber="11">complete</step>
        <step stepnumber="2">complete</step>
        <step stepnumber="3">complete</step>
    </user>
    <user number="0775543754">
        <step stepnumber="1">complete</step>
        <step stepnumber="2">complete</step>
    </user>
    <user number="0777743059">
        <step stepnumber="1">complete</step>
    </user>
</users>

produces the wanted, correct result:

11

Do note: using the xs:integer(.) above is necessary if we want to find the maximum of values as integers. Without it the maximum will be found on the values as strings and 3 will be bigger than 11.

In XPath 1.0 the following XPath expression returns the wanted maximum value:

/*/user[@number=$pNum]/step
            [not(@stepnumber
                <
                 ../step/@stepnumber
                 )
            ]
              /@stepnumber
Dimitre Novatchev