开发者

How to generate xml_builder ruby code from an XML file

开发者 https://www.devze.com 2023-01-26 01:59 出处:网络
I\'ve got an xml file.How could I generate xml_builder ruby code out of that fil开发者_如何学Ce?

I've got an xml file. How could I generate xml_builder ruby code out of that fil开发者_如何学Ce?

Notice - I'm sort of going backwards here (instead of generating xml, I'm generating ruby code).

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:

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. That's a language constructed exactly for such purposes - transforming XMLs.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消