XSLT - 添加新元素和属性

XSLT - add new element and attribute

我有 xml 如下,

<doc>
    <a ref="style1"><b>Test1</b></a>
    <a ref="style1"><b>Test2</b></a>
    <a ref="style2"><b>Test3</b></a>
</doc>

我需要在具有属性 "style1".

<a> 个节点中添加新属性和新节点

所以我写了下面的xsl,

//add attribute
<xsl:template match="a[@ref='style1']">
        <xsl:copy>
            <xsl:attribute name="id">myId</xsl:attribute>
        </xsl:copy>
    </xsl:template>

   //add new node
    <xsl:template match="a[@ref='style1']" priority="1">
        <xsl:copy>
            <newNode></newNode>
        </xsl:copy>
        <xsl:next-match/>
    </xsl:template>

我需要像上面那样创建两个模板(要求)。

但我目前的输出如下,

<doc>
    <a><newNode/></a><a id="myId"/>
    <a><newNode/></a><a id="myId"/>
    <a ref="style2"><b>Test2</b></a>
</doc>

如您所见,<a> 个节点增加了一倍。并且 <b> 个节点已经消失。但是我的预期输出是这样的,

<doc>
    <a id="myId"><newNode/><b>Test1</b>/a>
    <a id="myId"><newNode/><b>Test2</b>/a>
    <a ref="style2"><b>Test3</b></a>
</doc>

如何组织我的代码以获得高于预期的输出?

首先,您应该只在其中一个模板中使用 xsl:copy - 否则您将复制节点。

接下来,您必须在添加任何子节点之前添加属性。

最后,为了在父节点中同时拥有新属性和现有的子节点,您必须将相关说明放在 xsl:copy 元素中:

XSLT 2.0

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

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

<xsl:template match="a[@ref='style1']">
    <xsl:attribute name="id">myId</xsl:attribute>
</xsl:template>

<xsl:template match="a[@ref='style1']" priority="1">
    <xsl:copy>
        <xsl:next-match/>
        <newNode/>
        <xsl:apply-templates select="node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

结果

<?xml version="1.0" encoding="UTF-8"?>
<doc>
   <a id="myId">
      <newNode/>
      <b>Test1</b>
   </a>
   <a id="myId">
      <newNode/>
      <b>Test2</b>
   </a>
   <a ref="style2">
      <b>Test3</b>
   </a>
</doc>