簡體   English   中英

為什么xpath位置選擇表達式會返回多個節點?

[英]Why would an xpath position selection expression return multiple nodes?

在使用xpath(時間不長)時,我遇到了一些奇怪的事情。

xml的縮短版本(完整的xml在這里,並且在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測試儀上進行測試,我得到了相同的結果。

可能是什么問題呢?

兩個表達式分別代表其父級的第一個routemessage子級。 1你所有的route都是兄弟姐妹共享一個body父母,所以第一個被返回,只有那個。 但是,每個route包含自己的一組message子節點,其中第一個message子節點將為每個route節點返回。

如果需要匹配整個XML文檔中的第一個message元素,請使用:

(//message)[1]

括號告訴處理器找到匹配//message節點,然后在選擇這些節點中的第一個之后出現[1]謂詞。 沒有它們, [1]謂詞將簡單地基於其父節點的子節點進行操作。


1 因為我是一個CSS選擇器junkie:XPath表達式的選擇器副本分別是route:nth-of-type(1)message:nth-of-type(1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM