XSLT:复制和修改

pmf*_*pmf 1 xml xslt-2.0

我有一个不属于任何其他重复和修改答案的用例。

我有以下 XML 片段:

<Elements>
    <Irrelevant/>
    <Item>
        <Misc. subelements>
        <Name>A</Name>
        <Misc. subelements>
    </Item>
    <Irrelevant/>
    <Item>
        <Misc. subelements>
        <Name>B</Name>
        <Misc. subelements>
    </Item>
</Elements>
Run Code Online (Sandbox Code Playgroud)

并且需要将其转换为以下片段(后缀“_x”是通过传入的模板参数注入的,但对于答案,可以假设始终为“_x”):

<Elements>
    <Irrelevant/>
    <Item>
        <Misc. subelements (copied as-is)>
        <Name>A</Name>
        <Misc. subelements (copied as-is)>
    </Item>
    <Item>
        <Misc. subelements (copied as-is)>
        <Name>A_x</Name>
        <Misc. subelements (copied as-is)>
    </Item>
    <Irrelevant/>
    <Item>
        <Misc. subelements (copied as-is)>
        <Name>B</Name>
        <Misc. subelements (copied as-is)>
    </Item>
    <Item>
        <Misc. subelements (copied as-is)>
        <Name>B_x</Name>
        <Misc. subelements (copied as-is)>
    </Item>
</Elements>
Run Code Online (Sandbox Code Playgroud)

即每个Item都以原始形式复制一次,以修改后的形式复制一次。我只复制原始表单或仅复制修改后的表单没有问题,但是区分当前上下文是复制为原始格式还是修改后的内容是一个挑战。

Mar*_*nen 5

从身份转换模板开始

<xsl:template match="@* | node()" mode="#all">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()" mode="#current"/>
  </xsl:copy>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

然后为Item元素添加模板

<xsl:template match="Item">
  <xsl:copy-of select="."/>
  <xsl:copy>
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates select="node()" mode="change"/>
  </xsl:copy>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

然后为Namemode 中的元素编写模板change

<xsl:template match="Name" mode="change">
  <xsl:copy>
    <xsl:value-of select="concat(., $suffix)"/>
  </xsl:copy>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

带有全局参数<xsl:param name="suffix" select="'_x'"/>