Ruby XML
Ruby allows us to work with XML files with ease. In this tutorial, we will learn how to work with XML files in Ruby.
Syntax
Parsing XML document
To parse an XML document in Ruby we use the REXML
library. Here is the syntax for parsing an XML document:
require 'rexml/document'
include REXML
file = File.open("path/to/file.xml")
doc = Document.new file
file.close
Writing XML document
To generate an XML document in Ruby we use the Builder
library. Here is the syntax for writing an XML document:
require 'builder'
xml = Builder::XmlMarkup.new(:target => STDOUT)
xml.instruct! :xml, :version => "1.0", :encoding => "UTF-8"
xml.root do
xml.element1 "value1"
xml.element2 "value2"
end
Example
Here is an example of how to parse an XML document in Ruby:
require 'rexml/document'
include REXML
file = File.open("books.xml")
doc = Document.new file
file.close
doc.elements.each("catalog/book") do |book|
puts "Title: #{book.elements["title"].text}"
puts "Author: #{book.elements["author"].text}"
puts "Description: #{book.elements["description"].text}"
puts "Price: #{book.elements["price"].text}"
puts "------------------------------------------"
end
Output
Title: Harry Potter
Author: J.K. Rowling
Description: This is a book about a young boy who discovers he is a wizard.
Price: 19.99
------------------------------------------
Title: The Lord of the Rings
Author: J.R.R. Tolkien
Description: This trilogy is an epic adventure story set in the fantasy world of Middle-earth.
Price: 24.99
------------------------------------------
Explanation
In the above example, we are parsing an XML file containing information about books. We open the file using File.open
method and pass it to REXML::Document.new
constructor which creates an object of REXML::Document
class.
We then iterate over all <book>
elements using doc.elements.each("catalog/book")
method. Within the loop, we use book.elements["element_name"].text
to access the value of different elements within the <book>
element.
Use
XML is a popular format for data exchange and storage. In Ruby, we can easily parse and generate XML files using the REXML
and Builder
libraries respectively. XML files are used widely in web services, data exchange between applications, data storage, and many other applications.
Important Points
- Ruby provides built-in support for working with XML files.
REXML
library is used for parsing XML documents.Builder
library is used for generating XML documents.REXML::Document
represents an entire XML document.REXML::Element
represents an XML element.doc.elements.each
method is used to iterate over elements.el.elements["element_name"].text
is used to access element's text contents.- XML is widely used for data exchange and storage.
Summary
In this tutorial, we learned how to work with XML files in Ruby. We discovered that we can easily parse and generate XML files in Ruby using REXML
and Builder
libraries respectively. We also learned that XML is a popular format for data exchange and storage.