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 a beginner to XPath. I want to get the student with the overall highest ID (so 99999 in the example), not from each school. I can't change my python code which is
tree.xpath(" ... ")
I can only modify the xpath. I have tried "//student[not(../student/id > id)]
but this gives me highest id students from respective schools. What I want is the overall highest ID. How should I modify my xpath?
Edited : How do I write starting from the school level? I mean what if I want the school name which "highest ID" student exits?
What about:
//student[not(../../school/student/id > id)]
Or, more simply:
//student[not(//student/id > id)]
To get the <school/>
element with the highest student ID, I believe this will work:
//school[student[not(//student/id > id)]]
Use:
/schools/school[student[not(../../school/student/id > id)]]/name
Or shorter (just for this schema):
/*/school[*/id[not(//id > .)]]/name
Just for completeness... If you could had XPath 2.0 available, you could use max()
, as in:
/*/school[*/id = max(//id)]/name
It's a little easier than in XPath 1.0.
However AFAIK you do not have XPath 2.0 available in Python. So go with @cdhowie's or @Alejandro's answer.
精彩评论