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.

  <user >
    <!-- name of employee -->
    <!-- salary of employee -->
  <user >
require 'nokogiri'

file = 'users.xml'

  # read XML file
  xml_string =
  object = Nokogiri::XML(xml_string)

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

In this example

  • Import module, require Nokogiri
  • Read the xml using, 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 = 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) }
          xml.send(key, value)

file = 'result.xml'

  # 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}"

In this example,

  • import Nokogiri module
  • Declare an XML object that contains the ruby object
  • 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.