简体   繁体   English

如何从XML文件生成xml_builder红宝石代码

[英]How to generate xml_builder ruby code from an XML file

I've got an xml file. 我有一个xml文件。 How could I generate xml_builder ruby code out of that file? 如何从该文件中生成xml_builder红宝石代码?

Notice - I'm sort of going backwards here (instead of generating xml, I'm generating ruby code). 注意-我有点倒退(不是生成xml,而是生成ruby代码)。

Pretty formatting isn't a big deal - I can always run it through a formatter later. 漂亮的格式化并不重要-我以后总是可以通过格式化程序运行它。

It's sort of impossible, not unlike if you asked "how to generate Ruby script that outputs number 3 ", for the answer could be: 这是不可能的,就像您是否询问“如何生成输出3 Ruby脚本”一样,答案可能是:

puts 3

or 要么

puts 2+1

or 要么

puts [1,2,3].count

etc. 等等

So, one answer to your question would be: 因此,您的问题的一个答案将是:

xml = File.read('your.xml')
puts "puts <<EOF\n#{xml}\nEOF"

Anyway, if you would just want to generate Builder based script which just generates your XML node-for-node, I guess it would be easiest using XSLT. 无论如何,如果您只想生成基于Builder的脚本,该脚本仅生成您的XML逐节点,我想使用XSLT会最简单。 That's a language constructed exactly for such purposes - transforming XMLs. 正是出于这种目的而构建的一种语言-转换XML。

Here's what I eventually came up with: 这是我最终想到的:

#!/usr/bin/env ruby

require "rexml/document"

filename = ARGV[0]

if filename
  f = File.read(filename)
else
  raise "Couldn't read file: `#{filename}'"
end

doc = REXML::Document.new(f)

def self.output_hash(attributes={})
  count = attributes.size
  str = ""
  index = 0

  attributes.each do |key, value|
    if index == 0
      str << " "
    end

    str << "#{key.inspect} => "
    str << "#{value.inspect}"

    if index + 1 < count
      str << ", "
    end

    index += 1
  end

  str
end

def self.make_xml_builder(doc, str = "")
  doc.each do |element|
    if element.respond_to?(:name)
      str << "xml.#{element.name}"
      str << "#{output_hash(element.attributes)}"

      if element.length > 0
        str << " do \n"

        make_xml_builder(element, str)
        str << "end\n"
      else
        str << "\n"
      end
    elsif element.class == REXML::Text
      string = element.to_s

      string.gsub!("\n", "")
      string.gsub!("\t", "")

      if !string.empty?
        str << "xml.text!(#{string.inspect})\n"
      end
    end
  end

  str
end

puts make_xml_builder(doc)

After generating that, I then formatted it in Emacs. 生成该文件后,然后在Emacs中对其进行格式化。

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

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