mrh53
mrh53

Reputation: 35

XPath: how to select a subset of children of the current node

I am practicing with XPath and having a hard time understanding some concepts.

From the snippet below I wish to select the w1ident and w1slavetype elements of the w1slave node whose element w1slavename has the value 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>

The XPath expression //w1slave[w1slavename='livingroom']/w1ident works, as does replacing w1ident with w1slavetype.

But once I have selected the parent node with //w1slave[w1slavename='livingroom'], is there a compact means of requesting specific children without having to repeat the initial selection?

Like

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

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

works, but feels cumbersome.

Upvotes: 3

Views: 1869

Answers (2)

Daniel Haley
Daniel Haley

Reputation: 52848

You could use the self:: axis in a predicate:

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

Also, if you're using XPath 2.0 you can ditch the predicate and just use the union (|) in parens:

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

Upvotes: 5

eLRuLL
eLRuLL

Reputation: 18799

w1ident:

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

w1slavetype

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

Upvotes: 0

Related Questions