使用 xpath 查找父节点的位置



如何使用xpath获取父节点在整个文档中的位置?

假设我有以下 xml:

<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
</catalog>

我有一个XSLT将其转换为HTML,如下所示(仅代码段):

<xsl:template match="/">
<html>
  <body>  
  <xsl:apply-templates/>  
  </body>
  </html>
</xsl:template>
<xsl:template match="cd">
  <p>
    <xsl:number format="1. "/><br/>
    <xsl:apply-templates select="title"/>  
    <xsl:apply-templates select="artist"/>
  </p>
</xsl:template>
<xsl:template match="title">
  <xsl:number format="1" select="????" /><br/>
  Title: <span style="color:#ff0000">
  <xsl:value-of select="."/></span>
  <br />
</xsl:template>

我应该在????的位置写什么才能获得文档中父 cd 标签的位置。我尝试了许多表达方式,但似乎没有任何效果。可能是我完全做错了。

  1. <xsl:number format="1" select="catalog/cd/preceding-sibling::..[position()]" />
  2. <xsl:number format="1" select="./parent::..[position()]" /><br/>
  3. <xsl:value-of select="count(cd/preceding-sibling::*)+1" /><br/>

我将第二个解释为选择当前节点的父轴,然后告诉当前节点的父节点的位置。为什么它不起作用?正确的方法是什么。

仅供参考:我希望代码能够打印当前标题标签的父 cd 标签的位置 uder 处理。

请有人告诉我如何做到这一点。

count(../preceding-sibling::cd) + 1

您可以在此处运行它(请注意,我删除了您输出的其他数字,只是为了清楚起见)。

您走对了路,但请记住,谓词仅用于筛选节点,而不用于返回信息。所以:

../*[position()]

。有效地说"给我找有职位的父母"。它返回节点,而不是位置本身。谓词只是一个筛选器。

在任何情况下,使用 position() 都存在缺陷,它只能用于返回当前上下文节点的位置 - 而不是另一个节点。

Utkanos 的答案工作正常,但我的经验是,当 xml 文档很大时,这可能会导致性能问题。

在这种情况下,您可以简单地在参数中传递父级的位置。

<xsl:template match="/">
<html>
  <body>  
  <xsl:apply-templates/>  
  </body>
  </html>
</xsl:template>
<xsl:template match="cd">
  <p>
    <xsl:number format="1. "/><br/>
    <xsl:apply-templates select="title">  
        <xsl:with-param name="parent_position" select="position()"/> <!-- Send here -->
    </xsl:apply-templates>
    <xsl:apply-templates select="artist"/>
  </p>
</xsl:template>
<xsl:template match="title">
  <xsl:param name="parent_position"/> <!-- Receive here -->
  <xsl:number format="1" select="$parent_position"/><br/>
  Title: <span style="color:#ff0000">
  <xsl:value-of select="."/></span>
  <br />
</xsl:template>

结果:

<html xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><body>
  <p>1. <br>1<br>
  Title: <span style="color:#ff0000">Empire Burlesque</span><br>Bob Dylan</p>
  <p>2. <br>1<br>
  Title: <span style="color:#ff0000">Hide your heart</span><br>Bonnie Tyler</p>
</body></html>
  <xsl:number format="1" select="????" /> 

我应该在????的地方写什么才能获得父母的位置 文档中的 cd 标记。

首先,上述 XSLT 指令在语法上是非法的 -- <xsl:number>指令没有(不能)具有 select 属性

用途

   <xsl:number format="1" count="cd" /> 

最新更新