Find the position of an element within its parent with XSLT / XPath

久未见 提交于 2019-12-05 00:02:22
Tomalak

You could use

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

or even, generically,

<xsl:value-of select="count(preceding-sibling::*[name() = name(current())])" />

Of course this approach will not work if you process a list of nodes that is not uniform, i.e.:

<xsl:apply-templates select="here/foo|/somewhere/else/bar" />

Position information is lost in such a case, unless you store it in a variable and pass that to the called template:

<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>

but obviously that would mean some code rewriting, which I realize you want to avoid.


Final hint: position() does not tell you the position of the node within its parent. It tells you the position of the current node relative to the list of nodes you are processing right now.

If you only process (i.e. "apply templates to" or "loop over") nodes within one parent, this happens to be the same thing. If you don't, it's not.

Final hint #2: This

<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>

is is equivalent to this:

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

but the latter works without destroying the meaning of position(). Calling a template does not change context, so . will refer to the correct node withing the called template.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!