user3106228
user3106228

Reputation: 15

xpath expression to compare and evaluate value based on condition

<School>
    <Child_One>
        <Subject>
            <name>computers</name>
            <marks>55</marks>
            <name>mathematics</name>
            <marks>44</marks>
        </Subject>
        <Child_One>
            <Child_Two>
                <name>computers</name>
                <marks>66</marks>
                <name>mathematics</name>
                <marks>77</marks>
            </Child_Two>
</School>

Can anybody help me to find the Child_One subject name, in which he got highest marks

Thanks

Upvotes: 0

Views: 191

Answers (1)

Mark Veenstra
Mark Veenstra

Reputation: 4739

First of all a few formatting things:

  • Your XML is not quite well formatted. It should have the same start and end tags
  • I believe the Subject element should look different then posted
  • When posting a input XML, don't use backticks, but indent the XML with 4 spaces to format it well on Stackoverflow

I used and changed the input XML to this:

<?xml version="1.0" encoding="UTF-8"?>
<School>
    <Child_One>
        <Subject>
            <name>computers</name>
            <marks>55</marks>
        </Subject>
        <Subject>
            <name>mathematics</name>
            <marks>44</marks>
        </Subject>
    </Child_One>
    <Child_Two>
        <Subject>
            <name>computers</name>
            <marks>66</marks>
        </Subject>
        <Subject>
            <name>mathematics</name>
            <marks>77</marks>
        </Subject>
    </Child_Two>
</School>

With XPath 2.0 you can use the following the find the max value:

/School/Child_One/Subject[marks = max(/School/Child_One/Subject/marks)]/name

With XPath 1.0 you can use the following (replace < with > to find minimum):

/School/Child_One/Subject[not(marks < /School/Child_One/Subject/marks)][1]/name

Upvotes: 1

Related Questions