8

Does anyone know of an easy to use Ruby XML writer out there? I just need to write some simple XML and I'm having trouble finding one that's straightforward.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Tony R
  • 11,224
  • 23
  • 76
  • 101
  • REXML doesn't look too scary... anyone have an opinion on it? – Tony R Oct 12 '10 at 05:58
  • 1
    I was an REXML fan for a long time, but as it's Ruby based whereas Nokogiri relies on libxml2 and C, Nokogiri is hella faster and is my hands-down favorite for XML handling in Ruby these days. The Nokogiri::Builder is particularly nice. – Phrogz Feb 09 '11 at 05:17
  • Thanks, I ended up using RubyGems builder. It's very very simple and worked like a charm. – Tony R Feb 10 '11 at 01:39
  • Possible duplicate of [Write to XML in ruby](http://stackoverflow.com/questions/1244255/write-to-xml-in-ruby) – Helen Mar 22 '16 at 20:13

2 Answers2

9

builder is the canonical XML writer for Ruby. You can get it from RubyGems:

$ gem install builder

Here's an example:

require 'builder'
xml = Builder::XmlMarkup.new(:indent => 2)
puts xml.root {
  xml.products {
    xml.widget {
      xml.id 10
      xml.name 'Awesome Widget'
    }
  }
}

Here's the output:

<root>
  <products>
    <widget>
      <id>10</id>
      <name>Awesome Widget</name>
    </widget>
  </products>
</root>
wuputah
  • 11,285
  • 1
  • 43
  • 60
7

Nokogiri has a nice XML builder. This is from the Nokogiri site: http://nokogiri.org/Nokogiri/XML/Builder.html

require 'nokogiri'
builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.products {
      xml.widget {
        xml.id_ "10"
        xml.name "Awesome widget"
      }
    }
  }
end
puts builder.to_xml
# >> <?xml version="1.0"?>
# >> <root>
# >>   <products>
# >>     <widget>
# >>       <id>10</id>
# >>       <name>Awesome widget</name>
# >>     </widget>
# >>   </products>
# >> </root>
the Tin Man
  • 158,662
  • 42
  • 215
  • 303