Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xml xsl:for-each循环内的计数器_Xml_Xslt_Loops - Fatal编程技术网

Xml xsl:for-each循环内的计数器

Xml xsl:for-each循环内的计数器,xml,xslt,loops,Xml,Xslt,Loops,如何在xsl:for中为每个循环获取一个计数器,该计数器将反映当前已处理元素的数量。 例如,我的源XML是 <books> <book> <title>The Unbearable Lightness of Being </title> </book> <book> <title>Narcissus and Goldmund</title>

如何在xsl:for中为每个循环获取一个计数器,该计数器将反映当前已处理元素的数量。
例如,我的源XML是

<books>
    <book>
        <title>The Unbearable Lightness of Being </title>
    </book>
    <book>
        <title>Narcissus and Goldmund</title>
    </book>
    <book>
        <title>Choke</title>
    </book>
</books>

存在的无法忍受的轻
水仙与金门
窒息
我想得到的是:

<newBooks>
    <newBook>
        <countNo>1</countNo>
        <title>The Unbearable Lightness of Being </title>
    </newBook>
    <newBook>
        <countNo>2</countNo>
        <title>Narcissus and Goldmund</title>
    </newBook>
    <newBook>
        <countNo>3</countNo>
        <title>Choke</title>
    </newBook>
</newBooks>

1.
存在的无法忍受的轻
2.
水仙与金门
3.
窒息
要修改的XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <newBooks>
            <xsl:for-each select="books/book">
                <newBook>
                    <countNo>???</countNo>
                    <title>
                        <xsl:value-of select="title"/>
                    </title>
                </newBook>
            </xsl:for-each>
        </newBooks>
    </xsl:template>
</xsl:stylesheet>

???
所以问题是用什么来代替???。是否有任何标准关键字,或者我是否必须声明一个变量并在循环中递增它

由于问题很长,我可能希望有一行或一个词的答案:)

position()
。例如:

<countNo><xsl:value-of select="position()" /></countNo>


尝试在???的位置插入

注意“1”-这是数字格式。更多信息:

请尝试:

<xsl:value-of select="count(preceding-sibling::*) + 1" />


编辑-在那里大脑冻结,position()更简单

您还可以在position()上运行条件语句,这在许多情况下都非常有用

例如

 <xsl:if test="(position( )) = 1">
     //Show header only once
    </xsl:if>

//只显示一次标题

谢谢,这也是一篇有趣的文章。当需要一些格式时,我可能会使用这种方法XSLT 1.0版本:
这一切都很好,很好,直到您必须在xsl:中为每个添加一个类似xsl:if的过滤器。那么position()就没用了,你需要合适的计数器。@Mike Stavrov,这不是问题的一部分!不能涵盖所有situation@redsquare对的加上我的两分钱。我必须编写一个XSL扩展函数来解决我描述的情况。也许我应该向这里的人询问更好的解决方案。@MikeStarov那么如果
xsl:for each
中有
xsl:if
,该怎么办?什么是“适当的柜台”?您能指出一些资源吗?@lajarre您可以编写一个自定义扩展函数,从XSL调用。您还可以进行两次传递处理。处理一次并保存到xsl:variable。然后在xsl变量内容上应用模板,并使用position()添加编号。如果您有诸如xsl:sort之类的筛选器,则此操作将失败,因为第一个项目可能不是第一个要处理的项目。仍然可能有用,特别是如果您是基于position()以外的条件进行选择的话+1.
 <xsl:if test="(position( )) = 1">
     //Show header only once
    </xsl:if>