Phete
Phete

Reputation:

Write to XML in ruby

I am completely new to Ruby. All I want is to produce a simple XML file.

<?xml version="1.0" encoding="ASCII"?>
<product>
   <name>Test</name>
</product>

That's it.

Upvotes: 37

Views: 34114

Answers (4)

Mike Woodhouse
Mike Woodhouse

Reputation: 52316

Builder should probably be your first stopping point:

require 'builder'

def product_xml
  xml = Builder::XmlMarkup.new( :indent => 2 )
  xml.instruct! :xml, :encoding => "ASCII"
  xml.product do |p|
    p.name "Test"
  end
end

puts product_xml

produces this:

<?xml version="1.0" encoding="ASCII"?>
<product>
  <name>Test</name>
</product>

which looks about right to me.

Some Builder references:

Upvotes: 68

sepp2k
sepp2k

Reputation: 370112

You can use builder to generate xml.

Upvotes: 9

nikolayp
nikolayp

Reputation: 17919

Simply with Nokogiri::XML::Builder

require 'nokogiri'

builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') 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" encoding="UTF-8"?>
<root>
  <products>
    <widget>
      <id>10</id>
      <name>Awesome widget</name>
    </widget>
  </products>
</root>

Upvotes: 24

Peer Allan
Peer Allan

Reputation: 4004

Here are a couple more options for constructing XML in Ruby

REXML - built-in but is very slow especially when dealing with large documents

Nokogiri - newer and faster, installs as a rubygem

LibXML-Ruby - built on the C libxml library, also installs as a rubygem

If you can't install rubygems then REXML is your best options. If you are going to be creating large complex XML docs then Nokogiri or LibXML-Ruby is what you would want to use.

Upvotes: 5

Related Questions