Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the siblings of a node with Nokogiri

Tags:

ruby

nokogiri

Is there a way to find a specific value in a node and then return all its sibling values?

For example, I would like to find find the id node that contains ID 5678 and then get the email address and all images associated with ID 5678.

Nokogiri::XML.parse(File.open('info.xml'))

Here's a sample XML file.

<xmlcontainer>
  <details>
    <id>1234</id>
    <email>[email protected]</email>
    <image>images/1.jpg</image>
    <image>images/2.jpg</image>
    <image>images/3.jpg</image>
  </details>
  <details>
    <id>5678</id>   
    <email>[email protected]</email>
    <image>images/4.jpg</image>
    <image>images/5.jpg</image>
  </details>
  <details>
    <id>9011</id>   
    <email>[email protected]</email>
    <image>images/6.jpg</image>
    <image>images/7.jpg</image>
  </details>
</xmlcontainer>
like image 362
dullmcgee Avatar asked May 30 '13 04:05

dullmcgee


2 Answers

You can use ~, which is the css general sibling selector:

doc.search('id[text()="5678"] ~ *').map &:text
#=> ["[email protected]", "images/4.jpg", "images/5.jpg"]

It's a little bit weird to use css with xml but it's so much easier to look at (than xpath).

like image 114
pguardiario Avatar answered Sep 28 '22 05:09

pguardiario


require 'nokogiri'
doc = Nokogiri::XML.parse(File.open('info.xml'))
details = doc.css('details').find{|node| node.css('id').text == "5678"}
email = details.css('email').text # => "[email protected]"
images = details.css('image').map(&:text) # => ["images/4.jpg", "images/5.jpg"]

Update: There are shorter, arguably better, ways to grab the details node you want:

details = doc.at('details:has(id[text()="5678"])')

or

details = doc.search('id[text()="5678"] ~ *')

Those are both courtesy of pguardiario.

like image 29
Darshan Rivka Whittle Avatar answered Sep 28 '22 05:09

Darshan Rivka Whittle