How to generate XML file using Ruby and Builder::XMLMarkup templates?
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:
- How do I tell the Ruby program which is the te开发者_运维问答mplate I want to use? and
- 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.
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.
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.
精彩评论