简体   繁体   中英

how to select max xml attribute based on its attribute value start with “pro_” in xslt?

I have a weird requirement to get the max value that starts with specified string.Below is my sample source code,As we have seen the book element has an attribute called id ,as we have seen,some value of the id attribute are start with "pro_",such as pro_60 , pro_55 ,while the other attribute value are just pure number,such as 70 , 40 .

So my question is how to get the attribute value that starts with pro_ and the number is the max number .In this example the max number starts with pro_ is 65 ,so the expected result is pro_65 ,I can do it in my code ,but I am wondering can we do it just by using ?Any help is very greatful!

XPath version is 1.0 .

<?xml version="1.0" encoding="UTF-8"?>
 <datas>
    <books>
        <book id="pro_60">Java</book>
        <book id="pro_55">Golang</book>
        <book id="pro_40">PHP</book>
        <book id="pro_65">C++</book>
        <book id="pro_55">Python</book>
        <book id="70">Javascript</book>
        <book id="40">HTML5</book>
    </books>
</datas>

Using XPath 2.0:

/datas/books/book/@id[starts-with(., 'pro_')][not(../../book/@id/number(substring-after(., 'pro_')) > number(substring-after(., 'pro_')))]

As it depends on the feature of using functions calls in the last step of a path to compute a sequence of atomic values it can not be directly translated to XPath 1.0.

A shorter XPath 2.0 expression :

max(/*/*/*/@id[starts-with(.,'pro_')]/number(substring(.,5)))

This just calculates the maximum value.

To select all elements with id attributes that have this maximum value, use :

(/*/*/*[@id = concat('pro_', string(max(/*/*/*/@id[starts-with(.,'pro_')]/number(substring(.,5)))))]

As for XPath 1.0, this cannot be computed using a single XPath 1.0 expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM