9

I have a project that I am working on and I do not know much about Rails or Ruby.

I need to generate an XML file from user input. Can some direct me to any resource that can show me how to do this pretty quickly and easily?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ironmantis7x
  • 807
  • 2
  • 23
  • 58
  • There's not much to go on here, so I'll have to recommend in generalities. See : http://stackoverflow.com/questions/2309011/how-do-i-render-a-builder-template-in-ruby-on-rails – Jesse Wolgamott Jun 25 '13 at 22:30

2 Answers2

21

The Nokogiri gem has a nice interface for creating XML from scratch. It's powerful while still easy to use. It's my preference:

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

Will output:

<?xml version="1.0"?>
<root>
  <products>
    <widget>
      <id>10</id>
      <name>Awesome widget</name>
    </widget>
  </products>
</root>

Also, Ox does this too. Here's a sample from the documenation:

require 'ox'

doc = Ox::Document.new(:version => '1.0')

top = Ox::Element.new('top')
top[:name] = 'sample'
doc << top

mid = Ox::Element.new('middle')
mid[:name] = 'second'
top << mid

bot = Ox::Element.new('bottom')
bot[:name] = 'third'
mid << bot

xml = Ox.dump(doc)

# xml =
# <top name="sample">
#   <middle name="second">
#     <bottom name="third"/>
#   </middle>
# </top>
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
5

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>

Source: http://www.jakobbeyer.de/xml-with-nokogiri

David Okwii
  • 7,352
  • 2
  • 36
  • 29