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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With