我在“组”节点中。从中,我想找到这样的“项目”节点,其“ id”属性等于当前“组”节点的“ ref_item_id”属性值。因此,在我的情况下,通过位于“组”节点B中,我希望将“项目”节点A作为输出。这有效:
<xsl:value-of select="preceding-sibling::item[@id='1']/@description"/>
但这并没有(不提供任何东西):
<xsl:value-of select="preceding-sibling::item[@id=@ref_item_id]/@description"/>
当我键入:
<xsl:value-of select="@ref_item_id"/>
结果是“ 1”。因此,此属性确定是可访问的,但是我无法从上面的XPath表达式中找到它的路径。我尝试了很多“ ../”组合,但无法正常工作。
要测试的代码:http://www.xmlplayground.com/7l42fo
完整的XML:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item description="A" id="1"/>
<item description="C" id="2"/>
<group description="B" ref_item_id="1"/>
</root>
完整的XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="no"/>
<xsl:template match="root">
<xsl:for-each select="group">
<xsl:value-of select="preceding-sibling::item[@id=@ref_item_id]/@description"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
最佳答案
这与上下文有关。输入谓词后,上下文将立即成为该谓词当前正在过滤的节点,而不再是模板所匹配的节点。
您有两个选择-使用变量缓存外部范围数据并在谓词中引用该变量
<xsl:variable name='ref_item_id' select='@ref_item_id' />
<xsl:value-of select="preceding-sibling::item[@id=$ref_item_id]/@description"/>
或使用
current()
函数<xsl:value-of select="preceding-sibling::item[@id=current()/@ref_item_id]/@description"/>
关于xslt - 表达式中的XPath相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11280974/