XSLT用于复制具有不同属性的元素

时间:2014-11-11 16:15:42

标签: xml xslt

我需要创建一个来自

的XSLT转换

输入

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

要, 的输出

<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>

也就是说,pizza中以cheese_开头的所有元素都必须重复,并修改name元素以附加到tasty_字词}。

我有一个匹配器工作,<xsl:template match="node()[starts-with(@name, 'cheese_')]">但我不知道如何复制元素和修改属性。我之前没有完成XSLT工作,所以我不确定copycopy-to是否适合复制具有不同属性的元素。

2 个答案:

答案 0 :(得分:2)

我自己回答这个问题,因为我从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>

答案 1 :(得分:0)

另一种选择:

<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>