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

时间:2019-06-16 21:15:03

标签: xml xslt iteration immutability

给出以下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>

有没有更合适的方法来达到这个结果?

1 个答案:

答案 0 :(得分:1)

使用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

相关问题