tags:

views:

61

answers:

2

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

+4  A: 

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
+2  A: 

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>
Greg
Even I (who dislikes ruby) was able to pick up on Nokogiri's xml API pretty easily.
C Johnson
It's definitely a heck of a lot better than some other languages' XML creation modules or doing it by hand.
Greg