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.
Asked
Active
Viewed 2,713 times
8
-
REXML doesn't look too scary... anyone have an opinion on it? – Tony R Oct 12 '10 at 05:58
-
1I 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 Answers
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
-
Even I (who dislikes ruby) was able to pick up on Nokogiri's xml API pretty easily. – C.J. Oct 20 '10 at 16:02
-
It's definitely a heck of a lot better than some other languages' XML creation modules or doing it by hand. – the Tin Man Oct 20 '10 at 22:24