0

I have a problem on how to use max() function on XPath,

If consider following xml, I need to select the <tr> element which has maximum number of child <td> in it.

<doc>
    <table>
        <tbody>
            <tr>
                <td>aa</td>
                <td>bb</td>
                <td>cc</td>
                <td>dd</td>
            </tr>
            <tr>
                <td>nn</td>
                <td>oo</td>
            </tr>
            <tr>
                <td>qq</td>
                <td>rr</td>
                <td>ss</td>
                <td>tt</td>
                <td>uu</td>
                <td>vv</td>
                <td>xx</td>
                <td>yy</td>
                <td>zz</td>
            </tr>
        </tbody>
    </table>
</doc>

SO I wrote following xpath query

tr[max(count(child::td))]

But it return no result. can anyone suggest me a query that I can get <tr> which has maximum number of child <td>s ?

2
  • What should happen if multiple trs have the same number of tds (and that is the maximum)? Commented Oct 6, 2015 at 7:42
  • @Damien_The_Unbeliever , then the both <tr> should be selected Commented Oct 6, 2015 at 7:48

1 Answer 1

2

I think that this expression gives you what you want:

//tr[count(./td)>=count(following-sibling::tr/td) and
     count(./td)>=count(preceding-sibling::tr/td)]

That is, we want the count of the current nodes tds to be greater or equal to the count of any preceding node's tds and any following nodes tds.

You may want to adjust the starting point (I just went for any tr by starting with //) and depending on the relationships required, the sibling axes might need to be change to plain following and preceding.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.