数字子元素

时间:2019-03-13 10:36:03

标签: xslt

我正在尝试显示XML“ 2D列表”,如下所示:

<list1>
  <list2>a</list2>
  <list2>b</list2>
  <list2>c</list2>
  <list2>d</list2>
</list1>
<list1>
  <list2>e</list2>
  <list2>f</list2>
  <list2>g</list2>
  <list2>h</list2>
  <list2>i</list2>
  <list2>j</list2>
</list1>

我希望它显示如下:

01 a
02 b
03 c
04 d
05 e
06 f
07 g
08 h
09 i
10 j

我最初想的是在两个for-each的外部都有一个xsl:variable并将其递增,但是变量是不可变的。 该怎么办?

预先感谢

4 个答案:

答案 0 :(得分:1)

这里不需要TYPE_1,甚至不需要一个以上的xsl:variable(或xsl:for-each)。您可以一次选择所有xsl:apply-templates个元素,然后使用list2获得编号,因为position()是基于节点在所选节点集中的位置,而不是位置在文档树中。

position()

这假设您的XML格式正确,并且所有<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:output method="text" /> <xsl:template match="/*"> <xsl:apply-templates select="list1/list2" /> </xsl:template> <xsl:template match="list2"> <xsl:value-of select="concat(format-number(position(), '00'), ' ', ., '&#10;')" /> </xsl:template> </xsl:stylesheet> 元素都在单个父元素中。

请参见http://xsltfiddle.liberty-development.net/gWvjQf9

答案 1 :(得分:1)

另一种可能的方法是:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="xml" indent="yes" />
<xsl:strip-space elements="*" />

<xsl:template match="/root">
    <xsl:variable name="items" select="//list1/list2" />

    <xsl:for-each select="list1">
        <xsl:for-each select="list2">

            <xsl:variable name="id" select="generate-id()" />
            <xsl:for-each select="$items">
                <xsl:if test="generate-id() = $id">
                    <xsl:value-of select="position()" />
                    <xsl:value-of select="concat(' ',.)" />
                    <xsl:text>&#10;</xsl:text>
                </xsl:if>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

http://xsltransform.net/eieE3Q8/1

答案 2 :(得分:1)

我很惊讶没有人提到使用xsl:number。这是我通常需要为列表编号的常用方法。

示例...

XML输入

<doc>
    <list1>
        <list2>a</list2>
        <list2>b</list2>
        <list2>c</list2>
        <list2>d</list2>
    </list1>
    <list1>
        <list2>e</list2>
        <list2>f</list2>
        <list2>g</list2>
        <list2>h</list2>
        <list2>i</list2>
        <list2>j</list2>
    </list1>
</doc>

XSLT 1.0 (在其他版本中也是如此。)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="list2">
    <xsl:number level="any" format="01 "/>
    <xsl:value-of select="concat(.,'&#xA;')"/>
  </xsl:template>

</xsl:stylesheet>

输出

01 a
02 b
03 c
04 d
05 e
06 f
07 g
08 h
09 i
10 j

提琴:http://xsltfiddle.liberty-development.net/gWvjQfa/1

答案 3 :(得分:0)

<xsl:template match="/">
<xsl:apply-templates select="list1/list2"/>
</xsl:template>

<xsl:template match="//list2">
<xsl:value-of select="concat(format-number(position(), '00'), ' ', ., '&#10;')" />
</xsl:template>
相关问题