XSLT - 更改属性并同时应用动态 ID

XSLT - Change attribute and apply dynamic id same time

我有如下 xml 文件,

<doc>
  <a ref="Foot"></a>
  <a ref="Foot"></a>
  <a ref="Foot"></a>
  <a ref="End"></a>
  <a ref="End"></a>
  <a ref="End"></a>
  <a ref="Head"></a>
  <a ref="Head"></a>
<doc>

我的要求是向具有 "End" 属性的 <a> 节点添加动态递增 id 属性。并将 "Foot" 属性更改为 "End" 因此结果文档将是

<doc>
  <a ref="End" id="1"></a>
  <a ref="End" id="2"></a>
  <a ref="End" id="3"></a>
  <a ref="End" id="4"></a>
  <a ref="End" id="5"></a>
  <a ref="End" id="6"></a>
  <a ref="Head"></a>
  <a ref="Head"></a>
<doc>

我能够将动态 ID 添加到节点并使用 "End" 更改 "Foot" 属性,但该 ID 仅添加到之前具有 "End" 属性的节点。具有属性 "Foot" 的节点不添加 id。我当前的输出如下,

<doc>
  <a ref="End"></a>
  <a ref="End"></a>
  <a ref="End"></a>
  <a ref="End" id="1"></a>
  <a ref="End" id="2"></a>
  <a ref="End" id="3"></a>
  <a ref="Head"></a>
  <a ref="Head"></a>
<doc>

我的xsl代码如下,

 //change attribute "Foot" to attribute "End" 
 <xsl:template match="a/@ref[. = 'Foot']">
        <xsl:attribute name="id">End</xsl:attribute>
 </xsl:template>


//adds dynamic id's to foot node
<xsl:template match="a/@ref[.='End']">
   <xsl:attribute name="id">
        <xsl:number count="a[@ref='End']" level="any"></xsl:number>
   </xsl:attribute>
</xsl:template>

我的问题是如何将 id 添加到以前具有属性 "Foot" 的前三个节点。 有可能将模板应用于 <a> (<xsl:template match="a">) 节点并增加 id 但这不会完成这项工作,因为如果我这样做 <a> 具有属性 "Head" 也是应用 ID。

我想我可以使用 xls 变量和增量值之类的东西,但我在 xslt 方面的经验较少,我想不出正确的方法我应该怎么做

任何人都可以建议我一个答案,我该怎么做?

提前致谢。

尝试:

<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='Foot' or @ref='End']">
    <a ref="End">
        <xsl:attribute name="id">
            <xsl:number count="a[@ref='Foot' or @ref='End']"/>
        </xsl:attribute>
    </a>
</xsl:template>

</xsl:stylesheet>