简体   繁体   English

如何使用Ruby和Builder :: XMLMarkup模板生成XML文件?

[英]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). 众所周知,使用Rails可以使用Builder :: XMLMarkup模板以XML格式(而不是HTML)(使用response_to命令)提供HTTP响应。 My problem is that I would like to use the Builder::XMLMarkup templating system not with Rails but with Ruby only (ie a standalone program that generates/outputs an XML file from an XML template). 我的问题是我不想将Builder :: XMLMarkup模板系统与Rails一起使用,而仅与Ruby一起使用(即从XML模板生成/输出XML文件的独立程序)。 The question is then twofold: 问题是双重的:

  1. How do I tell the Ruby program which is the template I want to use? 如何告诉Ruby程序我要使用的模板? and
  2. How do I tell the Builder class which is the output XML file ? 如何告诉Builder类是输出XML文件?

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. 已经有与Stackoverflow中类似的答案( 如何使用.xml.builder文件从XMLBuilder生成XML? ),但恐怕它仅对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: @output对象将包含您的xml标记:

<?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. github.com上的Builder文档提供了更多示例以及指向更多文档的链接。

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. 无论如何,我更喜欢使用libxml-ruby来解析和构建XML文档,但这是有品味的。

I used Tilt to do (the first part of) this. 我用Tilt做(第一部分)。 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. 这将为您提供xml的字符串表示形式。 At that point you can write it out to disk yourself. 此时,您可以自己将其写到磁盘上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM