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>
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With