温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - XSLT to transform in a XML some tags with the count of every tag
xml xslt

其他 - XSLT以XML形式转换一些标签,每个标签的数量

发布于 2020-04-07 23:47:13

如何转换具有以下内容的XML:

<info>
   .....
   <name>aaa</name>
</info>
<info>
   .....
   <name>bbb</name>
</info>
<info>
   .....
   <name>ccc</name>
</info>

用XSLT变成这样的东西:

<info>
   .....
   <name1>aaa</name1>
</info>
<info>
   .....
   <name2>bbb</name2>
</info>
<info>
   .....
   <name3>ccc</name3>
</info>

有人知道吗?谢谢!

查看更多

提问者
WDrgn
被浏览
45
Martin Honnen 2020-02-01 04:08

我建议使用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="info/name">
      <xsl:variable name="pos">
          <xsl:number count="info"/>
      </xsl:variable>
      <xsl:element name="{name()}{$pos}">
          <xsl:apply-templates/>
      </xsl:element>
  </xsl:template>

</xsl:stylesheet>

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

或者在XSLT 3中使用累加器(即使在流传输中也可以使用):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy" use-accumulators="info-count" streamable="yes"/>

  <xsl:accumulator name="info-count" as="xs:integer" initial-value="0" streamable="yes">
      <xsl:accumulator-rule match="info" select="$value + 1"/>
  </xsl:accumulator>

  <xsl:template match="info/name">
      <xsl:element name="{name()}{accumulator-before('info-count')}">
          <xsl:apply-templates/>
      </xsl:element>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/ejivJs7/1