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

时间:2013-09-02 20:16:38

标签: 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,桌面Java和几个在线xpath测试人员上进行测试,我得到了相同的结果。

可能是什么问题?

1 个答案:

答案 0 :(得分:8)

这两个表达式分别代表其父级的第一个routemessage子级。 1 所有route都是共享一个body的兄弟姐妹。 1}} parent,所以返回第一个而且只返回。但是,每个route都包含自己的message个子集,其中第一个为route个节点返回。

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

(//message)[1]

括号告诉处理器找到匹配//message的节点,然后选择第一个节点之后出现的[1]谓词。如果没有它们,[1]谓词将仅根据其父节点的子节点进行操作。


1 因为我是一个CSS选择器junkie:XPath表达式的选择器对应物分别是route:nth-of-type(1)message:nth-of-type(1) < / p>

相关问题