Kxrr
Kxrr

Reputation: 520

how to combine two nodes into one group in Xpath?

I have html like this:

<div>
    <div class="a">10</div>
    <div class="b">11</div>
    <div class="a">20</div>
    <div class="b">21</div>

</div>

Sometimes I use //div[@class="a" or @class="b"] to get four groups: [10, 11, 20, 21].

But this time I want to get something like this, two groups: ["10 11", "20 21"], could I?

I mean that how to combine two nodes(class a, class b) into one group?

Upvotes: 4

Views: 3036

Answers (2)

Michael Kay
Michael Kay

Reputation: 163458

XPath 1.0 has only four data types: node-set, string, number, and boolean. Your desired result is not an instance of one of these types, so it follows that no XPath 1.0 can return it. However, XPath 2.0 allows sequences of strings so as @LukasEder points out, it can be done with 2.0

Upvotes: 2

Lukas Eder
Lukas Eder

Reputation: 221106

This would be a working XPath 2.0 solution (running example):

//div[@class="a"]/concat(
    text(), 
    ' ', 
    string-join((following-sibling::div[@class="b"]/text())[1], '')
)

I don't think a solution with XPath 1.0 would be possible here.

Upvotes: 4

Related Questions