[英]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 & Revere Ave" />
</routeConfiguredForMessage>
<text>Stop moved across Revere During 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 & Revere Ave" />
</routeConfiguredForMessage>
<text>Stop moved across Revere During Construction</text>
</message>
</route>
</body>
表達方式
//route[1]
像我預期的那樣返回第一個route
節點。 但是,在嘗試選擇第一個message
節點時,使用
//message[1]
返回了多個message
節點而不是一個。
起初我認為這是一個平台問題,但在Android,桌面Java和幾個在線xpath測試儀上進行測試,我得到了相同的結果。
可能是什么問題呢?
兩個表達式分別代表其父級的第一個route
和message
子級。 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.