rubyxmlxml-builder

How to generate xml_builder ruby code from an XML file


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.


Solution

  • 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.