xml - 为什么 xpath 位置选择表达式会返回多个节点?

标签 xml xpath

在使用 xpath(时间不长)时,我遇到了一些奇怪的事情。

xml 的缩短版本(完整的 xml 是 here,快照在 pastebin 上可用):

<?xml version="1.0" encoding="utf-8" ?> 
<body copyright="All data copyright San Francisco Muni 2013.">
  <route tag="all">
    <message id="10268" creator="jflynn" startBoundary="1378121400000" startBoundaryStr="Mon, Sep 02 04:30:00 PDT 2013" endBoundary="1378191540000" endBoundaryStr="Mon, Sep 02 23:59:00 PDT 2013" sendToBuses="false">
      <text>Sunday schedules today.</text>
    </message>
  </route>
  <route tag="44">
    <message id="10221" creator="mlee" startBoundary="1377525600000" startBoundaryStr="Mon, Aug 26 07:00:00 PDT 2013" endBoundary="1382857140000" endBoundaryStr="Sat, Oct 26 23:59:00 PDT 2013" sendToBuses="false">
      <routeConfiguredForMessage tag="44">        <stop tag="6420" title="Silver Ave &amp; Revere Ave" />
</routeConfiguredForMessage>
      <text>Stop moved&#10;across Revere&#10;During&#10;Construction</text>
    </message>
    <message id="10222" creator="mlee" startBoundary="1377525600000" startBoundaryStr="Mon, Aug 26 07:00:00 PDT 2013" endBoundary="1382857140000" endBoundaryStr="Sat, Oct 26 23:59:00 PDT 2013" sendToBuses="false">
      <routeConfiguredForMessage tag="44">        <stop tag="6420" title="Silver Ave &amp; Revere Ave" />
</routeConfiguredForMessage>
      <text>Stop moved&#10;across Revere&#10;During&#10;Construction</text>
    </message>
  </route>
</body>

表达式

//route[1]

如我所料返回了第一个 route 节点。但是,当尝试选择第一个 message 节点时,使用

//message[1]

返回了多个 message 节点,而不是一个。

起初我认为这是一个平台问题,但在 Android、Desktop Java 和几个在线 xpath 测试仪上进行测试,我得到了相同的结果。

可能是什么问题?

最佳答案

这两个表达式分别表示其父级的第一个 routemessage 子级。1 你所有的 route 是共享单个 body 父级的 sibling ,因此返回其中的第一个并且仅返回那个。但是,每个 route 都包含自己的一组 message 子级,第一个子级会为每个 route 节点返回。

如果您需要匹配整个 XML 文档中的第一个 message 元素,请使用:

(//message)[1]

括号告诉处理器找到匹配//message 的节点,然后紧随其后的[1] 谓词从这些节点中挑选第一个。没有它们,[1] 谓词将简单地基于其父节点的子节点进行操作。


1 因为我是一个 CSS 选择器迷:你的 XPath 表达式对应的选择器是 route:nth-of-type(1)message:nth-of-type(1),分别。

关于xml - 为什么 xpath 位置选择表达式会返回多个节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18580200/

相关文章:

javascript - 为 iPad 等移动设备使用 jQuery 解析 XML

javascript - 用于选择所有文本节点的 XPath

R 和 xml2 : how to read text that is not in children nodes and read information even if node is missing

javascript - 在 node.js 中使用 XPath

c# - XPathDocument 是否加载整个 xml 文档?

java - 如何通过 DOM 从以下 XML 中获取第一个子标签

xml - 转换文本中的 XML 标签

python - 如何在 python 中编写带有命名空间的 XML 元素

python - 使用python搜索和替换xml/文本文件中的多行

python - 在scrapy python中使用非类标签进行选择