xslt - 使用 XSLT/XPath 查找元素在其父元素中的位置

标签 xslt xpath position exslt

除了重写大量 XSLT 代码(我不打算这样做)之外,当上下文被任意设置为其他内容时,有没有办法在其父元素中找到元素的位置?下面是一个例子:

<!-- Here are my records-->
<xsl:for-each select="/path/to/record">
  <xsl:variable name="record" select="."/>

  <!-- At this point, I could use position() -->
  <!-- Set the context to the current record -->
  <xsl:for-each select="$record">

    <!-- At this point, position() is meaningless because it's always 1 -->
    <xsl:call-template name="SomeTemplate"/>
  </xsl:for-each>
</xsl:for-each>


<!-- This template expects the current context being set to a record -->
<xsl:template name="SomeTemplate">

  <!-- it does stuff with the record's fields -->
  <xsl:value-of select="SomeRecordField"/>

  <!-- How to access the record's position in /path/to or in any other path? -->
</xsl:template>

注意:这是一个简化的例子。我有几个限制使我无法实现明显的解决方案,例如将新参数传递给 SomeTemplate等。我真的只能修改 SomeTemplate 的内部结构。 .

注意:我正在使用 Xalan 2.7.1 和 EXSLT .所以这些技巧是可用的

有任何想法吗?

最佳答案

你可以用

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

甚至,一般来说,
<xsl:value-of select="count(preceding-sibling::*[name() = name(current())])" />

当然,如果您处理不统一的节点列表,则此方法将不起作用,即:
<xsl:apply-templates select="here/foo|/somewhere/else/bar" />

在这种情况下,位置信息会丢失,除非您将其存储在变量中并将其传递给被调用的模板:
<xsl:variable name="pos" select="position()" />
<xsl:for-each select="$record">
  <xsl:call-template name="SomeTemplate">
    <xsl:with-param name="pos" select="$pos" />
  </xsl:call-template>
</xsl:for-each>

但显然这意味着一些代码重写,我意识到你想避免。

最后提示:position()不会告诉您节点在其父节点中的位置。它告诉您当前节点相对于您正在处理的节点列表的位置。

如果您只处理(即“将模板应用于”或“循环”)一个父节点中的节点,这恰好是同一件事。如果你不这样做,那就不是。

最后提示#2:这个
<xsl:for-each select="/path/to/record">
  <xsl:variable name="record" select="."/>
  <xsl:for-each select="$record">
    <xsl:call-template name="SomeTemplate"/>
  </xsl:for-each>
</xsl:for-each>

相当于:
<xsl:for-each select="/path/to/record">
  <xsl:call-template name="SomeTemplate"/>
</xsl:for-each>

但后者的工作不会破坏 position() 的含义.调用模板不会改变上下文,所以 .将使用被调用的模板引用正确的节点。

关于xslt - 使用 XSLT/XPath 查找元素在其父元素中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6759907/

相关文章:

html - 我怎样才能让 body 填满整个可用空间,而不仅仅是屏幕?

xml - 默认命名空间未正确转换

java - 如何使用Java(用于selenium自动化)获取段落标签内的文本(div/div/p)

java - 是否有任何 Java API 可以在运行时使用输入的 xml 模式和 xpath 表达式和数据的键值对生成 xml

oracle - 通过xmltype理解解释计划

android - 检查无线是否开启(即使没有连接到任何网络)

xml - XSLT 和position()

c# - 在 XSLT 中生成 GUID

xslt - 如何处理 XSLT 中的重复导入?

html - 工具提示底部定位