sanjay
sanjay

Reputation: 1020

using max() function XPath

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 ?

Upvotes: 0

Views: 537

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239704

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.

Upvotes: 2

Related Questions