Write to XML in ruby
Asked Answered
M

4

36

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.

Maclay answered 7/8, 2009 at 11:29 Comment(2)
Well, there you have it - save it to a file :PHathaway
I meant, using an object model.Maclay
C
67

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:

Cannelloni answered 7/8, 2009 at 13:45 Comment(2)
The API docs link seems to be dead (I think rubyforge.org itself is no more?). Is there an updated link available?Lougheed
@Lougheed docs are available at github.com/jimweirich/builder -- I've proposed an edit fixing the link in the original post, but it's pending review.Superiority
T
24

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>
Tortious answered 21/11, 2014 at 16:9 Comment(1)
This is probably the most simple example of Nokogiri I've seen yet. Awesome.Boehmer
C
9

You can use builder to generate xml.

Constipate answered 7/8, 2009 at 11:36 Comment(0)
O
5

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.

Orwin answered 7/8, 2009 at 12:19 Comment(3)
All these are really for parsing existing xml, you should use Builder to create xml.Valente
nokogiri got a builder also - not sure if it is any better but if you are doing both parsing and writing it may be sweet to use the same lib.Rubeola
Nokogiris builder seems focused on blocks. It does work but I've found Builder very helpful with building xml programaticallyAlleman

© 2022 - 2024 — McMap. All rights reserved.