Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Data Between Elements in Nokogiri

I'm trying to get the text between two elements in nokogiri and pair the data with the text in the element in front of it.

html  = 
"<website>
    <maindeck>
        1<card>Blood Crypt</card>
        2<card>Temple Garden</card>
    </maindeck>
    <maindeck>
        3<card>Angel of Serenity</card>
        4<card>Forest</card>
    </maindeck>
</website>"

I want to end up with an array like this

#=> [[1,"Blood Crypt"],[2,"Temple Garden"]]

A previous example provided this as an answer, but I'm unsure of what it does/ how to use it.

/*/div[1]/following-sibling::text()[1]

Original link : grabbing text between two elements in nokogiri?

like image 824
Hackling Avatar asked Nov 04 '22 12:11

Hackling


1 Answers

This works:

doc = Nokogiri::HTML(html)
doc.xpath('//maindeck[1]/text()').map { |n| [n.text.to_i, n.next.text] }
#=> [[1, "Blood Crypt"], [2, "Temple Garden"]]
like image 160
Chris Salzberg Avatar answered Nov 12 '22 12:11

Chris Salzberg