Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good and simple Ruby XML writer?

Tags:

xml

ruby

writer

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.

like image 885
Tony R Avatar asked Oct 12 '10 05:10

Tony R


2 Answers

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>
like image 176
wuputah Avatar answered Nov 06 '22 21:11

wuputah


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>
like image 42
the Tin Man Avatar answered Nov 06 '22 21:11

the Tin Man