This tutorial covers how to read, validate, and write XML files in the Ruby language.

In Ruby, Nokogiri is a popular gem module library to read and write XML files.

First, Install the gem module in a project using the below command.

gem install nokogiri

How to parse XML files in Ruby

Let’s have a users.xml file that contains the following content.

<users>
  <user >
    <id>1</id>
    <name>john</name>
    <!-- name of employee -->
    <salary>5000</salary>
    <!-- salary of employee -->
  </user>
  <user >
    <id>2</id>
    <name>Eric</name>
    <salary>3000</salary>
  </user>
  <user>
    <id>3</id>
    <name>Mark</name>
    <salary>5100</salary>
  </user>
</users>
require 'nokogiri'

file = 'users.xml'

begin
  # read XML file
  xml_string = File.read(file)
  object = Nokogiri::XML(xml_string)

  puts object.to_xml(indent: 2)
rescue => e
  puts "Failed to read XML file: #{e.message}"
end

In this example

  • Import module, require Nokogiri
  • Read the xml using File.read(), read into a ruby variable as a string, xml_string.
  • Convert the XML content to Ruby Object using the Nokogiri::XML method
  • the object is of type Nokogiri::XML::Document, representing XML document.
  • Convert a document to XML with pretty print using to_xml(indent: 2)
  • You can handle exceptions using begin and rescue to handle file io failures and invalid XML format.

How to Write to XML file in Ruby

This example converts the ruby object into XML format and writes to it.

require 'nokogiri'

xml_string =
  user: [
    { id=> 1, name=> "john", salary=> 5000 },
    { id=> 2, name=> "Eric", salary=> 3000 },
    { id=> 3, name=> "Mark", salary=> 5100 },
  ],
};

xml_builder = Nokogiri::XML::Builder.new do |xml|
  xml_string.each do |root, items|
    xml.send(root) do
      items.each do |key, value|
        if value.is_a?(Hash)
          value.each { |k, v| xml.send(k, v) }
        else
          xml.send(key, value)
        end
      end
    end
  end
end

file = 'result.xml'

begin
  # Write XML content to the file
  File.write(file, xml_builder.to_xml(indent: 2))
  puts "XML file created."
rescue => e
  puts "Failed to write XML file: #{e.message}"
end

In this example,

  • import Nokogiri module
  • Declare an XML object that contains the ruby object
  • Nokogiri::XML::Builder.new create XMl builder
  • Using the builder, Convert Ruby Object to XML formatted data
  • Finally, Write to a file using File.write with the to_xml(indent: 2) option
  • It creates an XML file
  • begin and rescue used to handle errors in writing to XML files.