Home > OS >  XSLT : How to Concatenate a value to global variable
XSLT : How to Concatenate a value to global variable

Time:11-24

Just I want to do simple concatenate. When i iterate values, just i want to get all Product names in one string and print that value.. Here is my XML:

<CartItems>
  <CartItem>
    <ProductPrice>605.0000</ProductPrice>
    <ProductWeight>2.2975</ProductWeight>
    <ProductID>722</ProductID>
    <VariantID>235</VariantID>
    <Quantity>1</Quantity>
    <ProductName>ProductName1</ProductName>
  </CartItem>
  <CartItem>
    <ProductPrice>349.9900</ProductPrice>
    <ProductWeight>6.1731</ProductWeight>
    <ProductID>070</ProductID>
    <VariantID>296</VariantID>
    <Quantity>1</Quantity>
    <ProductName>ProductName2</ProductName>
  </CartItem>
</CartItems>

here is my code:

          <xsl:template name="CartItemProductNames">
                <xsl:param name="Data" />
                <xsl:variable name="CombineProductName">
                    
                </xsl:variable>
                <xsl:for-each select="$Data">
                    <xsl:if test="position()=1">
                        -- set value in CombineProductName
                    </xsl:if>
                        {
                        'ProductName':'<xsl:value-of select="ProductName" disable-output-escaping="yes" />',
                    <xsl:variable name="ProductName" select="ProductName">
                    <xsl:value-of select="$Total_Amount"/>
                    </xsl:variable>,
                    'Combined':'<xsl:value-of select="concat($CombineProductName,', ', $ProductName)" />'
                    }

                </xsl:for-each>
                <xsl:value-of select="$CombineProductName" disable-output-escaping="yes" />
            </xsl:template>

And this ackage is being called like:

'$PRODUCTNAMES' ='<xsl:call-template name="CartItemProductNames">
                        <xsl:with-param name="Data" select="/root/CartItems/CartItem"/>
                    </xsl:call-template>',

Desired output:

'$PRODUCTNAMES':'{ProductName1, ProductName2, and more if there will be in list}'

I am new to xslt. Please help me to solve this problem.

CodePudding user response:

The result you show can be produced very easily using:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/CartItems">
    <xsl:text>'$PRODUCTNAMES':'{</xsl:text>
    <xsl:for-each select="CartItem">
        <xsl:value-of select="ProductName"/>
        <xsl:if test="position()!=last()">, </xsl:if>
    </xsl:for-each>
    <xsl:text>}'</xsl:text>
</xsl:template>

</xsl:stylesheet>

and even more easily in XSLT 2.0 or higher.

  • Related