Greg Symsym
Greg Symsym

Reputation: 101

How to compare the values of two nodes in XSLT

I'm aware this is probably a duplicate, but I'm going to try anyway :)

I have an XML file from which I get criteria values. The XML file looks like this:

<root>
<test>
    <criteria nom="DR">
        <abbr>DR</abbr>
        <value>0.123456</value>
    </criteria>
    <criteria nom="MOTA">
        <abbr>MOTA</abbr>
        <value>0.132465</value>
    </criteria>
    </criteria>
</test>
<test>
    <criteria nom="DR">
        <abbr>DR</abbr>
        <value>0.655425</value>
    </criteria>
    <criteria nom="MOTA">
        <abbr>MOTA</abbr>
        <value>0.766545</value>
    </criteria>
</test>
</root>

and I'm trying to compare the fields <value>. For now I'm trying to do it this way:

<xsl:variable name="pos" select="position()" />
<xsl:for-each select="/root/test[$pos]/criteria/value">
    <xsl:if test="/root/test[$pos-1]/criteria/value/text() &lt; /root/test[$pos]/criteria/value/text()">
        <td class = "GOOD"><xsl:value-of select="text()"/></td>
    </xsl:if>
    <xsl:if test="/root/test[$pos-1]/criteria/value/text() &gt; /root/test[$pos]/criteria/value/text()">
        <td class = "BAD"><xsl:value-of select="text()"/></td>
    </xsl:if>
</xsl:for-each>

but this isn't the right way to do it. How can I achieve this result?

Upvotes: 0

Views: 736

Answers (1)

Valdi_Bo
Valdi_Bo

Reputation: 30971

Assuming that the current element is value, a quite elegant way to refer to the "previous" value (within the current test element) is:

select="../preceding-sibling::*[1]/value"

For a working example see http://xsltransform.net/93nvfcY

Note that your source XML contains within each test element only one criteria element which has a preceding sibling, so for demontration purpose I extended it by additional criteria element in the first test.

Visit the above mentioned page and experiment with changing values of value elements in the source XML pane.

Upvotes: 1

Related Questions