XPath:如何选择当前节点的子集子集

时间:2017-01-05 21:21:32

标签: xml xpath

我正在使用XPath练习并且很难理解一些概念。

在下面的代码段中,我希望选择w1ident节点的w1slavetypew1slave元素,其元素w1slavename的值为livingroom

 <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正常工作,将w1ident替换为w1slavetype也是如此。

但是一旦我选择了//w1slave[w1slavename='livingroom']的父节点,是否有一种紧凑的方式来请求特定的孩子,而不必重复初始选择?

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

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

有效,但感觉很麻烦。

2 个答案:

答案 0 :(得分:4)

您可以在谓词中使用self::轴:

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

此外,如果你正在使用XPath 2.0,你可以抛弃谓词,只需在parens中使用union(|):

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

答案 1 :(得分:0)

w1ident:

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

w1slavetype

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