XML

suggest change

In Ruby, you can parse, query, and generate XML using either the built-in standard library REXML or the high-performance Nokogiri gem (which binds to native libxml2).

Nokogiri is the fastest and most feature-complete XML parser for Ruby.

gem install nokogiri

Reading and Querying with XPath and CSS Selectors

require 'nokogiri'

xml_data = <<~XML
  <?xml version="1.0" encoding="UTF-8"?>
  <catalog>
    <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <price currency="USD">44.95</price>
    </book>
    <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <price currency="USD">5.95</price>
    </book>
  </catalog>
XML

doc = Nokogiri::XML(xml_data)

# Query using CSS selectors
doc.css('catalog book').each do |book|
  id     = book['id']
  title  = book.at_css('title').text
  author = book.at_css('author').text
  price  = book.at_css('price').text
  currency = book.at_css('price')['currency']

  puts "Book [#{id}]: \"#{title}\" by #{author} ($#{price} #{currency})"
end

# Query using XPath
cheap_titles = doc.xpath("//book[price < 10.0]/title").map(&:text)
puts "Books under $10: #{cheap_titles}"

Generating XML with Nokogiri::XML::Builder

Nokogiri includes a DSL for constructing well-formed, indented XML documents:

require 'nokogiri'

builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
  xml.users {
    xml.user(id: '1', role: 'admin') {
      xml.name 'Alice'
      xml.email 'alice@example.com'
    }
    xml.user(id: '2', role: 'member') {
      xml.name 'Bob'
      xml.email 'bob@example.com'
    }
  }
end

puts builder.to_xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
  <user id="1" role="admin">
    <name>Alice</name>
    <email>alice@example.com</email>
  </user>
  <user id="2" role="member">
    <name>Bob</name>
    <email>bob@example.com</email>
  </user>
</users>

Parsing XML with Standard Library REXML

If your environment cannot install native gems, Ruby's standard library provides REXML:

require 'rexml/document'

xml_string = '<server host="127.0.0.1"><port>8080</port><status>active</status></server>'
doc = REXML::Document.new(xml_string)

# Access root and attributes
root = doc.root
puts "Host: #{root.attributes['host']}"

# Access child elements
puts "Port: #{root.elements['port'].text}"
puts "Status: #{root.elements['status'].text}"

Handling Namespaces

When parsing XML containing namespaces (like SOAP responses or RSS/Atom feeds), declare prefix mappings in your XPath queries:

require 'nokogiri'

soap_xml = <<~XML
  <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                 xmlns:m="http://example.com/order">
    <soap:Body>
      <m:GetOrderStatusResponse>
        <m:Status>Shipped</m:Status>
      </m:GetOrderStatusResponse>
    </soap:Body>
  </soap:Envelope>
XML

doc = Nokogiri::XML(soap_xml)

# Pass namespace mapping hash to xpath
status = doc.xpath('//m:Status', 'm' => 'http://example.com/order').text
puts "Order Status: #{status}" # Shipped

Security: Preventing XXE (XML External Entity) Attacks

When parsing untrusted XML, always prevent external entity resolution to guard against file disclosure or server-side request forgery (SSRF):

# Nokogiri by default disables network access during parsing (NONET flag)
doc = Nokogiri::XML(untrusted_xml) do |config|
  config.nonet      # Prevent network connections for external DTDs
  config.nodtdload  # Do not load external DTDs
end

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents