【问题标题】:XPath: how to select an element where the attribute value equals another element valueXPath:如何选择属性值等于另一个元素值的元素
【发布时间】:2014-11-09 14:05:23
【问题描述】:

我有以下 xml 并试图在其中找到所有链接关系: (xml sn-p)

<heading nodeid="LINK_installing_driver">Installing the driver</heading>
...
<link linktotargetid="LINK_installing_driver">Installing the driver</link>

我不能只比较属性值字符串,因为我不确定它们。所以我需要一个通用的 XPath 表达式。我想要 nodeid 与相应链接元素匹配的标题文本。

我尝试了以下方法:

<xsl:value-of select="heading[@nodeid = //link/@linktotargetid]"/>

【问题讨论】:

    标签: xml xslt xpath


    【解决方案1】:

    您的问题缺乏上下文。通常,最好使用 key 从 XML 文档的另一个分支中查找数据。

    例如,如果您在样式表的顶层定义以下键:

    <xsl:key name="head" match="heading" use="@nodeid" />
    

    然后您可以在link 的上下文中使用它来检索对应的heading 的值,例如

    <xsl:template match="link">
        ...
            <xsl:value-of select="key('head', @linktotargetid)" />
        ...
    </xsl:template>
    

    【讨论】:

    • 太棒了!奇迹般有效!抱歉缺少上下文
    【解决方案2】:

    您能否提供有关问题发生位置的更多信息?您的 XPath 看起来正确,我刚刚使用 XSLT 创建了一个 example

    <?xml version="1.0" encoding="UTF-8" ?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" doctype-public="XSLT-compat" 
                  omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
    <xsl:template match="/">
        <xsl:apply-templates/>
    </xsl:template>
    <xsl:template match="@*|node()">
       <xsl:value-of select="heading[@nodeid = //link/@linktotargetid]"/>
    </xsl:template>
    </xsl:stylesheet>  
    

    对于示例输入 XML

    <root>
      <heading nodeid="LINK_installing_driver">Installing the driver</heading>
       <link linktotargetid="LINK_installing_not_driver">Not Installing the driver</link>
       <link linktotargetid="LINK_installing_driver">Installing the driver</link>
    </root>
    

    显示正确的标题:Installing the driver

    【讨论】:

      猜你喜欢
      • 2022-10-14
      • 2011-03-13
      • 2012-12-24
      • 2011-07-10
      • 2020-03-08
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多