Harri
Harri

Reputation: 2732

XSL transform grandchild node values to element attribute value

Given following XML:

<test id="s1-t2" name="Lorem ipsum">
    ...
    <tags>
        <tag>foo</tag>
        <tag>bar</tag>
    </tags>
    ...
</test>

I'd like to append the node value of each tag element in name attribute of test element. So the resulting XML should be like this:

<test id="s1-t2" name="Lorem ipsum [foo][bar]">
    ...
    <tags>
        <tag>foo</tag>
        <tag>bar</tag>
    </tags>
    ...
</test>

The tags element (and its content) can remain in place, but it is not necessary.

So far I've tried something like this:

<xsl:template match="test">
    <test>
        <xsl:copy-of select="@*"/>
        <xsl:attribute name="name">
            <xsl:value-of select="tags/tag"/>
        </xsl:attribute>
        <xsl:apply-templates select="node()"/>
    </test>
</xsl:template>

but that does not work. And even if it would work, it would replace the name attribute and only with one tag. It's been too long since I last wrote any XSLT.

Upvotes: 0

Views: 278

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117100

I'd like to append the node value of each tag element in name attribute of test element.

Try it this way:

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="/test/@name">
    <xsl:attribute name="name">
        <xsl:value-of select="."/>
        <xsl:for-each select="../tags/tag">
            <xsl:text>[</xsl:text>
            <xsl:value-of select="."/>
            <xsl:text>]</xsl:text>
        </xsl:for-each>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

Upvotes: 2

Related Questions