在XSL中创建元素的略微修改副本

时间:2014-07-07 22:54:40

标签: xml regex xslt transformation

我想转换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>

我不知道如何将<node1>从转化变为动态的东西。

2 个答案:

答案 0 :(得分:0)

我找到了它!

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

答案 1 :(得分:0)

查尔斯,你是对的。但是&#34;规范&#34;这个问题的解决方案更像是这样:

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

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

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