Home > Blockchain >  XSLT 1.0 Pass the contents of one element to another
XSLT 1.0 Pass the contents of one element to another

Time:01-12

I have a requirement to use XSLT to process an XML file as is, but concatenating the values of repeating elements of one element and passing the concatenated string to another element.

The difficulty I am having is saving the concatenation as a parameter and being able to access that value in the target of the move.

eg. Original XML

<root>
    <someData>transform as is</someData>
    <target>
        <concatenatedElement/>
    </target>
    <someMoreData>transform as is</someMoreData>
    <source>
        <separateElement>valueX</separateElement>
        <separateElement>valueY</separateElement>
        <separateElement>valueZ</separateElement>
    </source>
</root>

Desired transformed XML:

<root>
    <someData>transform as is</someData>
    <target>
        <concatenatedElement>valueXvalueYvalueZ</concatenatedElement>
    </target>
    <someMoreData>transform as is</someMoreData>
</root>

The original XML is much larger than the example above, so I am already applying a template to transform the rest of the XML as it is. I've tried several methods including calling another template from within the "match" template but I can't access the values from the source block to send to the target block. Below is my latest attempt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:param name="separateValues">
        <xsl:for-each select="/root/source/separateElement">
            <xsl:value-of select="."/>
        </xsl:for-each>
    </xsl:param>
    <xsl:template match="/root/target">
        <xsl:param name="separateValues"/>
        <xsl:element name="target">
            <xsl:value-of select="$separateValues"/>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

CodePudding user response:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" />
  
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
  
    <xsl:template match="/root/target/concatenatedElement">
        <xsl:copy>
            <xsl:for-each select="/root/source/*">
                <xsl:value-of select="." />
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>
  
    <xsl:template match="/root/source" />

</xsl:stylesheet>

gives

<root>
    <someData>transform as is</someData>
    <target>
        <concatenatedElement>valueXvalueYvalueZ</concatenatedElement>
    </target>
    <someMoreData>transform as is</someMoreData>
</root>
  •  Tags:  
  • Related