0

I need to sort my tags in a XML file based on multiple different nodes. For example: Consider the following XML:

<root>
    <a>
        <b>12</b>
        <e>hello</e>
    </a> 
    <a>
        <b>11</b>
        <e>how</e>
    </a>
    <a>
        <c>13</c>
        <f>are</f>
    </a>
    <a>
        <b>21</b>
        <f>you</f>
    </a>
    <a>
        <d>22</d>
        <e>hello</e>
    </a>
    <a>
        <c>14</c>
        <f>hi</f>
    </a>
</root>

Now I need to find the maximum number from inside all the nodes inside a. I tried doing this:

<xsl:template match="root">
    <xsl:for-each select="a">
        <xsl:sort select="b | c | d" data-type="number" order="descending"/>   <!-- this gives me error-->
            <xsl:if test="position() = 1">
                <!-- how to access my node -->
            </xsl:if>
    </xsl:for-each>
</xsl:template>

How can I do my sorting and get the value form the first node after sorting?

Thnx in advance!!

Note: I am using XSLT 1.0.

2
  • what is your required output? Please see my answer below. Should you have a different requirement, feel free to edit your post. Commented Mar 24, 2014 at 6:23
  • @JoelM.Lamsen structure of the output is not important. I just need the maximum value. Commented Mar 24, 2014 at 6:27

1 Answer 1

2

This stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="root">
        <xsl:for-each select="a/*[string(number(.))!='NaN']">
            <xsl:sort select="." order="descending"/>
            <xsl:if test="position() = 1">
                <highest><xsl:copy-of select="."/></highest>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

when applied to the edited input XML above, outputs

<highest>
   <d>22</d>
</highest>
Sign up to request clarification or add additional context in comments.

6 Comments

plz see the updated XML. The nodes inside a may not always be nodes containing numbers. Other types of node may also be present.
I have edited my post. Please check if this suits your requirement.
yes, after tweaking the idea a little according to my XML I can use your solution. thank you very much.
what if i have to process the numbers before sorting them. For example, in the above xml the numbers had some units associated with them like m, cm, in etc. Now first I have to transform all of them in a single unit like cm and then sort them. How can I do that?
please post this as another question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.