RichK
RichK

Reputation: 11879

XSLT to duplicate elements with different a different attribute

I need to create an XSLT transform to go from

Input

<pizza>
    <pref name="cheese_cheddar" value="2" />
    <pref name="meat_chicken" value="5" />
    <pref name="cheese_edam" value="10" />
</pizza>

to, Output

<pizza>
    <pref name="cheese_cheddar" value="2" />
    <pref name="tasty_cheese_cheddar" value="2" />
    <pref name="meat_chicken" value="5" />
    <pref name="cheese_edam" value="10" />
    <pref name="tasty_cheese_edam" value="10" />
</pizza>

That is, all elements inside pizza that start with cheese_ need to be duplicated with the name element modified to append to word tasty_.

I've got a matcher working, <xsl:template match="node()[starts-with(@name, 'cheese_')]"> but I've no clue how to duplicate elements and modify an attribute. I've not done XSLT work before so I'm not sure if copy and copy-to are appropriate for duplicating elements with different attributes.

Upvotes: 1

Views: 740

Answers (2)

mmkd
mmkd

Reputation: 900

Another option:

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

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

    <xsl:template match="pref[starts-with(@name, 'cheese_')]">

        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>

        <xsl:element name="pref">
            <xsl:attribute name="name">
                <xsl:value-of select="concat('tasty_', @name)"/>
            </xsl:attribute>
            <xsl:attribute name="value">
                <xsl:value-of select="@value"/>
            </xsl:attribute>
        </xsl:element>

    </xsl:template>

</xsl:stylesheet>

Upvotes: 0

RichK
RichK

Reputation: 11879

I'm answering this myself, as I got a major clue from https://stackoverflow.com/a/17135323/255231

<?xml version="1.0" encoding="utf-8"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
<xsl:template match="node()[starts-with(@name, 'cheese_')]">
 <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:attribute name="name">tasty_<xsl:value-of select="@name"/></xsl:attribute>
        <xsl:apply-templates />
    </xsl:copy>
</xsl:template>
</xsl:transform>

Upvotes: 2

Related Questions