0

I've got an xml file. How could I generate xml_builder ruby code out of that file?

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.

smtlaissezfaire
  • 437
  • 2
  • 7
  • 18

2 Answers2

0

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.

Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
0

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
smtlaissezfaire
  • 437
  • 2
  • 7
  • 18