【问题标题】:Create slightly modificate copy of an element in XSL在 XSL 中创建元素的稍微修改的副本
【发布时间】:2014-08-28 13:29:29
【问题描述】:

我想转换一个 XML 文档并在某些属性上做一些正则表达式/替换。

这是 XML:

<node1>
    <node2>
        <item attrbitueToModify="Blabla"></item>
    </node2>
    <node3>
        <node4>
            <item attrbitueToModify="Blabla"></item>
        </node4>
    </node3>
<node1>

这里是变换

<xsl:template match="*" >
    <node1>
        <xsl:for-each select="attribute::*" >
            <xsl:choose>
                <xsl:when test="fn:name() = 'attrbitueToModify'">
                    <xsl:attribute name="attrbitueToModify" ><xsl:value-of select="replace(., 'blabla', 'replaced')" /></xsl:attribute>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:copy-of select="." />
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>

        <xsl:apply-templates select="*" />
    </node1>
</xsl:template>

我不知道如何将 &lt;node1&gt; 从转换变为动态。

【问题讨论】:

    标签: xml regex xslt transformation


    【解决方案1】:

    查尔斯,你说对了。但这个问题的“规范”解决方案更像是这样的:

    <xsl:template match="node()|@*">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>
    
    <xsl:template match="@attributeToModify">
      <xsl:attribute name="{name()}" select="replace(., 'blabla', 'replaced')"/>
    </xsl:template>
    

    第一个模板规则被称为“身份模板”,因为它复制所有内容不变,除非有更具体的规则另有说明。在 XSLT 3.0 中,您不需要写出身份模板,而是可以声明:

    <xsl:mode on-no-match="shallow-copy"/>
    

    【讨论】:

      【解决方案2】:

      我找到了!

      <xsl:template match="*" >
          <xsl:element name="{name(.)}">
              <xsl:for-each select="attribute::*" >
                  <xsl:choose>
                      <xsl:when test="fn:name() = 'attrbitueToModify'">
                          <xsl:attribute name="attrbitueToModify" ><xsl:value-of select="replace(., 'blabla', 'replaced')" /></xsl:attribute>
                      </xsl:when>
                      <xsl:otherwise>
                          <xsl:copy-of select="." />
                      </xsl:otherwise>
                  </xsl:choose>
              </xsl:for-each>
      
              <xsl:apply-templates select="*" />
          </xsl:element>
      </xsl:template>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多