2017-01-05 69 views
1

我正在練習XPath,並且很難理解一些概念。XPath:如何選擇當前節點的子集的一個子集

從下面我想選擇其元件w1slavename具有值livingroomw1slave節點的w1identw1slavetype元素片段。

<w1slave create="2017-01-05 12:39:41"> 
    <w1ident>28-0000000FBAA6</w1ident> 
    <w1identprefix>28</w1identprefix> 
    <w1slavetype>THERM_DS18B20</w1slavetype> 
    <w1slavename>familyroom</w1slavename> 
</w1slave> 
<w1slave create="2017-01-05 12:39:45"> 
    <w1ident>28-000005e2fdc3</w1ident> 
    <w1identprefix>28</w1identprefix> 
    <w1slavetype>THERM_DS18B20</w1slavetype> 
    <w1slavename>livingroom</w1slavename> 
</w1slave> 

XPath表達式//w1slave[w1slavename='livingroom']/w1ident作品一樣,與w1slavetype替換w1ident

但是,一旦我選擇了帶有//w1slave[w1slavename='livingroom']的父節點,是否有一種緊湊的方式來請求特定的孩子而不必重複初始選擇?

//w1slave[w1slavename='livingroom']/w1ident | 

//w1slave[w1slavename='livingroom']/w1slavetype 

作品,但感覺累贅。

+0

我是新來的stackexchange我不知道如何投票。 – mrh53

+0

不用擔心。一旦你的聲望達到15,你就可以投票。你已經過了一半了! –

回答

3

您可以使用self::軸謂詞:

//w1slave[w1slavename='livingroom']/*[self::w1ident or self::w1slavetype] 

另外,如果你使用的XPath 2.0,你可以拋棄謂詞並且只使用parens中的union(|):

//w1slave[w1slavename='livingroom']/(w1ident|w1slavetype) 
+0

謝謝。這兩個選項中的第一個可以工作,所以我的瀏覽器不能兼容XPath 2.0。 – mrh53

+0

@ mrh53 - 歡迎使用stackoverflow!是的,瀏覽器不符合XPath 2.0標準。另外,如果足夠了,請考慮[接受此答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。有關更多信息,另請參閱http://stackoverflow.com/help/someone-answers。 –

+1

感謝您的支持。 – mrh53

0

w1ident:

'//w1slavename[text()="familyroom"]/preceding-sibling::w1ident' 

w1slavetype

'//w1slavename[text()="familyroom"]/preceding-sibling::w1slavetype' 
+0

我喜歡選擇的格式,但有沒有辦法將兩個前面的兄弟姐妹合併爲一個查詢?例如,// w1slave [w1slavename ='livingroom']/*將返回從節點的所有子節點,但這比我想要的要多。我寧願不做兩個單獨的查詢。 – mrh53

相關問題