XPath to get the maximum ID

XML source:

<schools>
    <school>
        <name>School A</name>
        <student>
            <name>Student A</name>
            <id>12345</id>
        </student>
        <student>
            <name>Student B</name>
            <id>45678</id>
        </student>
    </school>
    <school>
        <name>School C</name>
        <student>
            <name>Student C</name>
            <id>91178</id>
        </student>
        <student>
            <name>Student D</name>
            <id>99999</id>
        </student>
    </school>
</schools>

I am still new to XPath. I want the student to get the highest ID (for example, 99999 in the example), and not in every school. I cannot change my python code which

tree.xpath(" ... ")

I can only change xpath. I tried "//student[not(../student/id > id)], but it gives me the highest students from the respective schools. I want this to be the highest identifier. How do I change my xpath?

Edited: How do I write starting at school level? I mean, what if I want the name of the school to come out of the “highest identifier” student?

+3
source share
3 answers

What about:

//student[not(../../school/student/id > id)]

Or simply put:

//student[not(//student/id > id)]

<school/> , , :

//school[student[not(//student/id > id)]]
+12

:

/schools/school[student[not(../../school/student/id > id)]]/name

( ):

/*/school[*/id[not(//id > .)]]/name
+2

Just for completeness ... If you could use XPath 2.0, you can use max(), as in:

/*/school[*/id = max(//id)]/name

This is a bit easier than XPath 1.0.

However, AFAIK you do not have XPath 2.0 available in Python. So go with the answer @cdhowie or @Alejandro.

+2
source

Source: https://habr.com/ru/post/1778707/


All Articles