如何获取父元素的位置 - XSL

joe*_*joe 1 xml xslt

我希望我能在xsl中做到以下几点,但不幸的是,parent/position()无效.

XSL

<xsl:template match="li">
  <bullet>
    <xsl:apply-templates/>
  </bullet>
  <!-- if this is the last bullet AND there are no more "p" tags, output footer -->
  <xsl:if test="count(ancestor::div/*) = parent/position()">
    <footer/>
  </xsl:if>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

XML

<html>
  <div>
    <p>There is an x number of me</p>
    <p>There is an x number of me</p>
    <p>There is an x number of me</p>
    <ul>
      <li>list item</li>
      <li>list item</li>
      <li>list item</li>
      <li>list item</li>
      <li>list item</li>
    </ul>
  </div>
</html>
Run Code Online (Sandbox Code Playgroud)

任何人有任何想法如何从弄清楚这个问题WITHIN我的模板匹配里?

谢谢!

mar*_*usk 5

您可以通过计算其前面的兄弟节点来查找源节点中父节点的位置:

<xsl:variable name="parent-position" 
              select="count(../preceding-sibling::*) + 1"/>
Run Code Online (Sandbox Code Playgroud)

如果要确定p父元素后面是否有任何元素ul,可以在不使用位置的情况下测试它:

<xsl:if test="../following-sibling:p">...</xsl:test>
Run Code Online (Sandbox Code Playgroud)

但是,正如Dimitre和Oliver所指出的那样,在处理父元素时添加页脚更符合XSLT的精神.此外,显示的XPath表达式仅关注原始源树中的顺序.如果您打算xsl:sort在处理之前过滤元素或重新排序,这些路径将无法按预期工作,因为它们将查看原始排序并包括源树中的所有节点.