xsl for-each循环中的条件增量

Conditional increment in xsl for-each loop

给定以下 XML 格式:

<?xml version="1.0"?>
<items>
  <id>7</id>
  <id></id>
  <id/>
  <id>9</id>
  <id/>
</items>

我想自动递减每个给定的 "id",最好使用 XSLT 1.0 版。

由于 XSL 中变量的不可变性,我只能想出以下解决方案:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <items>
      <xsl:for-each select="items/id[text()]">
        <id><xsl:value-of select="."/></id>
      </xsl:for-each>
      <xsl:for-each select="items/id[not(text())]">
        <id><xsl:value-of select="-position()"/></id>
      </xsl:for-each>
    </items>
  </xsl:template>
</xsl:stylesheet>

但这打破了元素的顺序。 我更喜欢这个结果 xml:

<?xml version="1.0"?>
<items>
  <id>7</id>
  <id>-1</id>
  <id>-2</id>
  <id>9</id>
  <id>-3</id>
</items>

有没有更合适的方法来实现这个结果?

使用xsl:number:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

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

  <xsl:template match="id[not(normalize-space())]">
      <xsl:copy>-<xsl:number count="id[not(normalize-space())]"/></xsl:copy>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/ej9EGcU