首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XSLT用不同的属性复制元素

XSLT用不同的属性复制元素
EN

Stack Overflow用户
提问于 2014-11-11 16:15:41
回答 2查看 553关注 0票数 1

我需要创建一个XSLT转换

输入

代码语言:javascript
复制
<pizza>
    <pref name="cheese_cheddar" value="2" />
    <pref name="meat_chicken" value="5" />
    <pref name="cheese_edam" value="10" />
</pizza>

输出

代码语言:javascript
复制
<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元素以附加到word tasty_

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-11 16:29:33

我自己回答这个问题,因为我从https://stackoverflow.com/a/17135323/255231得到了一个重要的线索

代码语言:javascript
复制
<?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>
票数 2
EN

Stack Overflow用户

发布于 2014-11-11 16:38:04

另一种选择:

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26869377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档