How to generate XML file using Ruby and Builder::XMLMarkup templates?

16,511

Solution 1

Here's a simple example showing the basics:

require 'builder'

@received_data = {:books => [{ :author => "John Doe", :title => "Doeisms" }, { :author => "Jane Doe", :title => "Doeisms II" }]}
@output = ""
xml = Builder::XmlMarkup.new(:target => @output, :indent => 1)

xml.instruct!
xml.books do
  @received_data[:books].each do |book|
    xml.book do
      xml.title book[:title]
      xml.author book[:author]
    end
  end
end

The @output object will contain your xml markup:

<?xml version="1.0" encoding="UTF-8"?>
<books>
 <book>
  <title>Doeisms</title>
  <author>John Doe</author>
 </book>
 <book>
  <title>Doeisms II</title>
  <author>Jane Doe</author>
 </book>
</books>

The Builder docs at github.com provide more examples and links to more documentation.

To select a specific template, you could pass arguments to your program for this decision.

Anyway, I prefer to use libxml-ruby to parse and build XML documents, but that's a matter of taste.

Solution 2

I used Tilt to do (the first part of) this. It's really easy:

require 'builder'
require 'tilt'
template = Tilt.new('templates/foo.builder')
output = template.render

That will get you a string representation of your xml. At that point you can write it out to disk yourself.

Share:
16,511
mgfernan
Author by

mgfernan

Researcher in Aerospace technology, programmer, project manager and Eternal Learner

Updated on June 26, 2022

Comments

  • mgfernan
    mgfernan almost 2 years

    As you all know, with Rails it is possible to use Builder::XMLMarkup templates to provide an http reponse in XML format instead of HTML (with the respond_to command). My problem is that I would like to use the Builder::XMLMarkup templating system not with Rails but with Ruby only (i.e. a standalone program that generates/outputs an XML file from an XML template). The question is then twofold:

    1. How do I tell the Ruby program which is the template I want to use? and
    2. How do I tell the Builder class which is the output XML file ?

    There is already a similar answer to that in Stackoverflow (How do I generate XML from XMLBuilder using a .xml.builder file?), but I am afraid it is only valid for Rails.

  • mgfernan
    mgfernan over 14 years
    Yes I have read it but I could not see any mention in how to actually create an XML using Builder templates with Ruby (not Rails)...
  • Mereghost
    Mereghost over 14 years
    I've expanded somewhat the answer. Take a look.
  • OpenCoderX
    OpenCoderX over 12 years
    I think he would like to know how to get it to the final file on the disk.