XSLT - 替换XML文档的重新部分(在任何级别)

JBa*_*uch 1 xslt

专业人士,我需要在以下文档中将'B'标签转换为'X'标签:

<a>
 <B marker="true">
  <c>
    <B marker="true">
      <d>
        <B marker="true">
        </B>
       <d>
    </B>
  </c>
 </B>
</a>
Run Code Online (Sandbox Code Playgroud)

注意重复出现的'B',它可以出现在动态XML的任何深度.这是我做的:

<xsl:template match="//*[@marker='true']">
    <X>
        <xsl:copy-of select="./node()"/>
    </X>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

它适用于最顶级的'B'标签,但忽略了所有嵌套标签.

我想我知道问题是什么 - 'copy-of'只是刷新最顶级'B'标签的内容,而不评估它.我可以做些什么来"复制"重新评估我的模板?

谢谢!巴鲁克.

Fla*_*ack 7

我会选择身份变换.

这段代码:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="B[@marker = 'true']">
        <X>
            <xsl:apply-templates/>
        </X>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

针对此XML输入:

<a>
    <B marker="true">
        <c test="test">
            testText
            <B marker="true">
                <d>
                    testText2
                    <B marker="true">
                        testText3
                    </B>
                </d>
            </B>
            testText4
        </c>
        testText5
    </B>
</a>
Run Code Online (Sandbox Code Playgroud)

将提供这个正确的结果:

<a>
    <X>
        <c test="test">
            testText
            <X>
                <d>
                    testText2
                    <X>
                        testText3
                    </X>
                </d></X>
            testText4
        </c>
        testText5
    </X>
</a>
Run Code Online (Sandbox Code Playgroud)

  • @Michael Kay,我更喜欢"身份变换与覆盖",但它是一样的. (2认同)