Har*_*eep 9 xml xslt xpath parent
如何使用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>
Run Code Online (Sandbox Code Playgroud)
我有一个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>
Run Code Online (Sandbox Code Playgroud)
我该怎么写在????的地方?获取文档中父CD标记的位置.我尝试过很多表达式,但似乎没有任何效果.可能是我完全错了.
<xsl:number format="1" select="catalog/cd/preceding-sibling::..[position()]" /><xsl:number format="1" select="./parent::..[position()]" /><br/><xsl:value-of select="count(cd/preceding-sibling::*)+1" /><br/>我将第二个解释为选择当前节点的父轴,然后告诉当前节点的父节点的位置.为什么不起作用?这样做的正确方法是什么.
仅供参考:我希望代码能够打印当前标题标签uder处理的父CD标签的位置.
请有人告诉我如何做到这一点.
Utk*_*nos 18
count(../preceding-sibling::cd) + 1
Run Code Online (Sandbox Code Playgroud)
你可以在这里运行它(注意我删除了你输出的另一个号码,只是为了清晰起见).
你是在正确的行,但请记住,谓词只用于过滤节点,而不是返回信息.所以:
../*[position()]
Run Code Online (Sandbox Code Playgroud)
...有效地说"找到有我职位的父母".它返回节点,而不是位置本身.谓词只是一个过滤器.
在任何情况下,存在与使用陷阱position(),并且它可以用于返回电流,上下文节点的位置仅 -不另一个节点.