Shivashankara K K
Shivashankara K K

Reputation: 35

XSLT: how to update the node of previous level for match

This is the sample Xml, i want to check if any RangeItem having Input as 'Else' (there will be only 1 else RangeItem) then i want to place that RangeItem's Output value to the value of Default, which is there one level up.

<ColorConverter>
            <Property ID="Default">#76D5F9</Property>
            <RangeItem>
              <Property ID="Name">RangeItem1</Property>
              <Property ID="Input">Else</Property>
              <Property ID="Output">#4A3737</Property>
            </RangeItem>
            <RangeItem>
              <Property ID="Name">RangeItem2</Property>
              <Property ID="Input">Equal</Property>
              <Property ID="Output">#FFFFFF</Property>
            </RangeItem>
 </ColorConverter>

Expected Output:

<ColorConverter>
            <Property ID="Default">#4A3737</Property>
            <RangeItem>
              <Property ID="Name">RangeItem1</Property>
              <Property ID="Input">Else</Property>
              <Property ID="Output">#4A3737</Property>
            </RangeItem>
            <RangeItem>
              <Property ID="Name">RangeItem2</Property>
              <Property ID="Input">Equal</Property>
              <Property ID="Output">#FFFFFF</Property>
            </RangeItem>
 </ColorConverter>

Please help me.

Upvotes: 0

Views: 58

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117165

If I understand correctly, you want to do:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="ColorConverter">
    <xsl:variable name="default-item" select="RangeItem[Property[@ID='Input']='Else']" />
    <xsl:copy>
        <Property ID="Default">
            <xsl:choose>
                <xsl:when test="$default-item">
                    <xsl:value-of select="$default-item/Property[@ID='Output']"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="Property[@ID='Default']"/>
                </xsl:otherwise>
            </xsl:choose>
        </Property>
        <xsl:apply-templates select="RangeItem"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions