by
back

create xml in ruby with nokogiri

Nokogiri is a wrapper around libxml2.

Gemfile

gem 'nokogiri'

To generate xml simple use the Nokogiri XML Builder like this

xml = Nokogiri::XML::Builder.new { |xml| 
    xml.body do
        xml.node1 "some string"
        xml.node2 123
        xml.node3 do
            xml.node3_1 "another string"
        end
        xml.node4 "with attributes", :attribute => "some attribute"
        xml.selfclosing
    end
}.to_xml

The result will look like

<?xml version="1.0"?>
<body>
  <node1>some string</node1>
  <node2>123</node2>
  <node3>
    <node3_1>another string</node3_1>
  </node3>
  <node4 attribute="some attribute">with attributes</node4>
  <selfclosing/>
</body>


comments powered by Disqus