Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the min/max value of an attribute under multiple nodes in XPath 1.0

Tags:

xml

xpath

Consider the following XML structure:

<a>
<b>
    <c>
        <d x="1"/>
        <d x="2"/>
        <d x="3"/>
        <d x="3"/>
        <d x="4"/>
    </c>
</b>
<b>
    <c>
        <d x="1"/>
        <d x="1"/>
        <d x="2"/>
        <d x="3"/>
        <d x="4"/>
        <d x="5"/>
        <d x="5"/>
    </c>
</b>
<b>
    <c>
        <d x="1"/>
        <d x="2"/>
        <d x="3"/>
        <d x="3"/>
        <d x="4"/>
        <d x="5"/>
        <d x="5"/>
    </c>
</b>

I'd like a XPath 1.0 statement to give me the minimum and maximum values of @x? So far I have the following for the minimum:

//a/b/c/d[not(preceding-sibling::d/@x <= @x) and not(following-sibling::d/@x <= @x)]/@x

which is close, but no cigar :-(

Any help greatly appreciated!

Thanks, J

like image 612
redmamoth Avatar asked Nov 25 '25 14:11

redmamoth


1 Answers

To fetch the maximum value, look for all attribute values for which there are not smaller ones. If there are multiple results, take the first one - they must be equal.

(//@x[not(. < //@x)])[1]

For the minimum value, just replace < by >.

For completeness reasons: if your XPath engine supports XPath 2.0 (or better), just use max(//@x) respecting min(//@x) which will probably be faster and more readable.

like image 184
Jens Erat Avatar answered Nov 27 '25 15:11

Jens Erat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!