【问题标题】:XSLT to duplicate elements with different a different attributeXSLT 复制具有不同属性的元素
【发布时间】:2015-01-08 06:23:51
【问题描述】:

我需要创建一个 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_

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

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      另一种选择:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-04
        • 2013-11-04
        • 2019-02-26
        • 1970-01-01
        • 1970-01-01
        • 2015-05-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多