Good and simple Ruby XML writer?
Asked Answered
E

2

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.

Evesham answered 12/10, 2010 at 5:44 Comment(4)
REXML doesn't look too scary... anyone have an opinion on it?Evesham
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.Eudiometer
Thanks, I ended up using RubyGems builder. It's very very simple and worked like a charm.Evesham
Possible duplicate of Write to XML in rubyTadeas
F
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>
Fiery answered 12/10, 2010 at 6:3 Comment(0)
T
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>
Twinberry answered 13/10, 2010 at 4:36 Comment(2)
Even I (who dislikes ruby) was able to pick up on Nokogiri's xml API pretty easily.Wesley
It's definitely a heck of a lot better than some other languages' XML creation modules or doing it by hand.Twinberry

© 2022 - 2024 — McMap. All rights reserved.