表达式中的XPath相对路径

one*_*run 1 xslt xpath

我在'组'节点.从中,我想找到这样的'item'节点,其'id'属性等于当前'group'节点'ref_item_id'属性值.所以在我的情况下,通过在'组'节点B中,我想要'item'节点A作为输出.这有效:

<xsl:value-of select="preceding-sibling::item[@id='1']/@description"/>
Run Code Online (Sandbox Code Playgroud)

但这不会(什么都不给):

<xsl:value-of select="preceding-sibling::item[@id=@ref_item_id]/@description"/>
Run Code Online (Sandbox Code Playgroud)

当我输入:

<xsl:value-of select="@ref_item_id"/>
Run Code Online (Sandbox Code Playgroud)

我的结果是"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>
Run Code Online (Sandbox Code Playgroud)

完整的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>
Run Code Online (Sandbox Code Playgroud)

Utk*_*nos 8

这与上下文有关.输入谓词后,上下文将成为谓词当前正在过滤的节点,而不再是模板匹配的节点.

您有两个选项 - 使用变量来缓存外部范围数据并在谓词中引用该变量

<xsl:variable name='ref_item_id' select='@ref_item_id' />
<xsl:value-of select="preceding-sibling::item[@id=$ref_item_id]/@description"/>
Run Code Online (Sandbox Code Playgroud)

或使用该current()功能

<xsl:value-of select="preceding-sibling::item[@id=current()/@ref_item_id]/@description"/>
Run Code Online (Sandbox Code Playgroud)

  • Nit但不知何故很重要,`current`是XSLT http://www.w3.org/TR/xslt20/#function-current中定义的函数,而不是XPath中定义的函数. (2认同)