How to Parse XML With Ruby

Stewart Nguyen Feb 02, 2024
  1. Use the gem install nokogiri to Install Gem nokogiri in Ruby
  2. Use the Gem nokogiri to ParseXML in Ruby
How to Parse XML With Ruby

The nokogiri is a ruby gem that parses XML and HTML. This article shows how to use it.

Use the gem install nokogiri to Install Gem nokogiri in Ruby

gem install nokogiri

Output:

Building native extensions. This could take a while...
Successfully installed nokogiri-1.10.10
Parsing documentation for nokogiri-1.10.10
Installing ri documentation for nokogiri-1.10.10
Done installing documentation for nokogiri after 4 seconds
1 gem installed

Use the Gem nokogiri to ParseXML in Ruby

Let’s put it to the test by parsing this XML document.

my_xml = <<~MYDOC
  <root>
    <person name="husband">Adam</person>
    <person name="wife">Eve</person>
  </root>
MYDOC
require 'nokogiri'

doc = Nokogiri::XML(my_xml)

Iteration on each element:

doc.elements.each { |e| puts e.name }

We could access the data at each node:

doc.at('person[name="husband"]').text
=> "Adam"
doc.at('person[name="wife"]').text
=> "Eve"