除了重写大量 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/