xsltoverwritexsl-variable

Overwrite the variable in xsl


I just need to overwrite the variable in xsl

Example:
x=0
if x=0
then
x=3

I need to change the value of variable.

I am very new to xsl, please help me how to achieve this. This may be silly but I don't have any idea..


Solution

  • The <xsl:variable> in xslt is not actual a variable. Which means it can not be changed after you have defined it and you can use it like this:

    lets say we have this xml with name test.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <client-list>
        <client>
            <name>person1</name>
        </client>
        <client>
            <name>person2</name>
        </client>
        <client>
            <name>person3</name>
        </client>
    </client-list>
    

    and we want to transform it to csv-like (comma separated values) but replacing the person1 with a hidden person with name person4. Then lets say we have this xml with name test.xsl which will be used to transform the test.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="text"/>
    
        <xsl:variable name="hiddenname">person4</xsl:variable>
    <!-- this template is for the root tag client-list of the test.xml -->
        <xsl:template match="/client-list">
    <!-- for each tag with name client you find, ... -->
            <xsl:for-each select="client">
    <!-- if the tag with name -name- don't have the value person1 just place its data, ... -->
                <xsl:if test="name != 'person1'">
                    <xsl:value-of select="name"/>
                </xsl:if>
    <!-- if have the value person1 place the data from the hiddenperson -->
                <xsl:if test="name = 'person1'">
                    <xsl:value-of select="$hiddenname"/>
                </xsl:if>
    <!-- and place a comma -->
            <xsl:text>,</xsl:text>
            </xsl:for-each>
        </xsl:template>
    </xsl:stylesheet>
    

    the results will be

    person4,person2,person3,
    

    I hope this will help you.