user2235494
user2235494

Reputation: 399

Sorting xslt nodes based on sibling

I am having some trouble getting this to work and I could really need some help. I want to store the smallest variable that has a sibling which is not null. I have a XML which looks like this:

<Root>
    <Item>
         <ValueOne>5</ValueOne>
         <Item>bababa</Item>
    </Item>
    <Item>
         <ValueOne>3</ValueOne>
         <Item>ababa</Item>
    </Item>
    <Item>
         <ValueOne>1</ValueOne>
         <Item/>
    </Item>
</Root>

I want the smallest ValueOne who's sibling Item has a value. I was thinking something like:

<xsl:variable name="var">
    <xsl:for-each select="Root/Item">
         <xsl:if test="not(/Item = '')">
             <xsl:sort data-type="text"/>
             <xsl:if test="position()=1">
                 <xsl:value-of select="/Item"/>
             </xsl:if>
         </xsl:if>
    </xsl:for-each>
</xsl:variable>

But this doesn't work and I am not sure why. As you might tell I'm not the best at xslt. I cannot rename anything in the xml or change the structure of it.

Upvotes: 0

Views: 71

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

Assuming those spaces and returns are non-essential, you could use:

<xsl:variable name="var">
    <xsl:for-each select="Root/Item[normalize-space(Item)]">
        <xsl:sort select="ValueOne" data-type="number" order="ascending"/>
        <xsl:if test="position()=1">
            <xsl:value-of select="normalize-space(ValueOne)"/>
        </xsl:if>
    </xsl:for-each>
</xsl:variable>

With all the redundant white space removed, this can be simplified to:

<xsl:variable name="var">
    <xsl:for-each select="Root/Item[Item/text()]">
        <xsl:sort select="ValueOne" data-type="number" order="ascending"/>
        <xsl:if test="position()=1">
            <xsl:value-of select="ValueOne"/>
        </xsl:if>
    </xsl:for-each>
</xsl:variable>

Upvotes: 1

Related Questions