You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何XPath表达式//note[last()]会选中XML中的两个<note>标签?

XPath表达式//note[last()]返回多个节点的原因解释

示例XML文档

<app>
    <welcome-message>Hi! This is xpather beta...</welcome-message>
    <abstract>
        This web app enables you to query XML/HTML documents with your
        browser in real time. It can generate queries for you too! 
    </abstract>
    <description>
        <subject>
            To generate an xpath query for a specific element,
            please hold CTRL and hover over it.
            An xpath is generated heuristically with the aim
            to be unambiguous and the shortest possible.
        </subject>
      <note>hey</note>
    </description>
    <extra-notes>
        <note>
            By default XML mode is used but if a document cannot
            be parsed as XML then HTML mode kicks in.
        </note>
        <note>
            Pasting documents bigger than 500kb may cause your
            browser become sluggish or unresponsive.
        </note>
    </extra-notes>
</app>

问题

使用XPath表达式//note[last()]时,返回了<description>下的<note>标签和<extra-notes>下的最后一个<note>标签。按理解,//note会获取所有<note>节点集,last()应选中该集合的最后一个节点,为何实际得到两个结果?

原因解析

核心是XPath的表达式优先级和上下文作用:

  • //note[last()]的执行逻辑并非先获取所有<note>节点再取集合最后一个。它的实际执行流程是:遍历文档中所有带有<note>子节点的父元素,对每个父元素,筛选出它自己的最后一个<note>子节点。
  • 在你的XML结构里:
    • <description>只有1个<note>子节点,这个节点就是该父元素下的最后一个,因此被选中;
    • <extra-notes>有2个<note>子节点,其中最后一个会被选中。
      所以最终返回这两个节点。
  • 如果你想获取所有<note>节点中的最后一个,需要用括号改变优先级,写成(//note)[last()]。括号会让//note先执行,生成所有<note>的节点集合,然后[last()]再从这个整体集合中选取最后一个节点。

内容的提问来源于stack exchange,提问作者sadcat_1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 20:42:50