xslt - 表达式中的XPath相对路径

标签 xslt xpath

我在“组”节点中。从中,我想找到这样的“项目”节点,其“ 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/

相关文章:

xslt - 根据所需长度分割字符串

c# - 样式问题 : LINQ or XPath to read in XML nodes

xpath - Selenium findByXpath 中的运算符不起作用

ruby capybara - 在运行时获取 xpath

xml - 节点计数和出现 - XSL

xml - XSLT:将节点向上移动一级

xslt - 我们如何将 XML 元素转换为 xslt 中的不同 namespace

xml - Robotframework:如何在选择字段中接收所有项目的列表?

c# - 使用 Linq To XML,获取所有叶子路径的方法?

java - 属性的 XSLT 格式-日期