gpt4 book ai didi

xml - 使用 xpath 查找父节点的位置

转载 作者:数据小太阳 更新时间:2023-10-29 01:42:41 26 4
gpt4 key购买 nike

如何使用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/>

我将 2nd 解释为选择当前节点的父轴,然后告诉当前节点的父节点的位置。为什么它不起作用?执行此操作的正确方法是什么。

仅供引用:我希望代码在处理过程中打印当前标题标签的父 cd 标签的位置。

谁能告诉我怎么做。

最佳答案

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

您可以 run it here (请注意,为了清楚起见,我删除了您输出的其他数字)。

您是对的,但请记住谓词仅用于过滤节点,而不用于返回信息。所以:

../*[position()]

...有效地说“给我找到有职位的 parent ”。它返回节点,而不是位置本身。谓词只是一个过滤器。

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

关于xml - 使用 xpath 查找父节点的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11273046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com