0

关于我的问题

position()函数返回整个文档中实际节点的位置,如何获得相对于选定节点的位置。假设我有 100 个城市的列表,并且我根据给定的过滤器列表排除了 10 个(请参阅问题),现在我想根据所选节点而不是原始文档位置来获得计数。

简单来说,这是一个计数器/增量问题,因为我看到计数器是不可能的。我们如何创建或使用现有函数来喜欢 position() 来获取节点在选定节点中的位置。

我希望我的问题很清楚。

编辑示例场景

  <xsl:template match="/">
    <xsl:apply-templates select="db:databaseChangeLog/db:changeSet[*[1][($excludes eq '' or not(@tableName = tokenize($excludes, ',')))]]"/> 
  </xsl:template>

   <xsl:template match="db:changeSet">
      ...
   </xsl:template>

我在哪里根据子节点属性名称选择父节点。

4

2 回答 2

1

你对position函数的描述是错误的。请参阅http://www.w3.org/TR/xslt20/#focus,特别是“上下文位置是当前正在处理的项目序列中上下文项目的位置。只要上下文项目发生变化,它就会发生变化。当xsl:apply-templates 或 xsl:for-each 等指令用于处理一系列项目,序列中的第一项以上下文位置 1 处理,第二项以上下文位置 2 处理,依此类推on.] 上下文位置由 XPath 表达式 position()" 返回。

例如,如果我们有<xsl:apply-templates select="cities/city[not(@abbr = $skip/abbr)]"/>并且我们position在模板匹配city元素中使用该函数,例如

<xsl:template match="city">
  <xsl:copy>
    <xsl:value-of select="position()"/>
  </xsl:copy>
</xsl:template>

我们会得到<city>1</city><city>2</city>等等。

于 2013-08-16T12:09:38.170 回答
1

我认为最好使用xsl:number. 使用xsl:number,您应该能够更轻松地排除元素。

这是一个小示例,显示了两者的结果position()xsl:number用于比较。

XML 输入

<cities>
    <city>City One</city>
    <city>City Two</city>
    <city>City Three</city>
    <city>City Four</city>
    <city>City Five</city>
    <city>City Six</city>
    <city>City Seven</city>
    <city>City Eight</city>
    <city>City Nine</city>
    <city>City Ten</city>
</cities>

XSLT 2.0(我认为 2.0 是安全的,因为问题被标记为 saxon 并且您在评论中使用了 tokenize 。)

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

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

    <xsl:variable name="exclude" select="('City Three','City Six','City Nine')"/>

    <xsl:template match="city[not(.=$exclude)]">
        <city position="{position()}">
            <xsl:attribute name="number">
                <xsl:number count="city[not(.=$exclude)]"/>
            </xsl:attribute>
            <xsl:value-of select="."/>
        </city>
    </xsl:template>

    <xsl:template match="city"/>

</xsl:stylesheet>

输出

<cities>
   <city position="1" number="1">City One</city>
   <city position="2" number="2">City Two</city>
   <city position="4" number="3">City Four</city>
   <city position="5" number="4">City Five</city>
   <city position="7" number="5">City Seven</city>
   <city position="8" number="6">City Eight</city>
   <city position="10" number="7">City Ten</city>
</cities>
于 2013-08-16T16:45:27.487 回答