ruby-on-railsrubyxmlxml-builder

What can I use to generate a local XML file?


I have a project that I am working on and I do not know much about Rails or Ruby.

I need to generate an XML file from user input. Can some direct me to any resource that can show me how to do this pretty quickly and easily?


Solution

  • The Nokogiri gem has a nice interface for creating XML from scratch. It's powerful while still easy to use. It's my preference:

    require 'nokogiri'
    builder = Nokogiri::XML::Builder.new do |xml|
      xml.root {
        xml.products {
          xml.widget {
            xml.id_ "10"
            xml.name "Awesome widget"
          }
        }
      }
    end
    puts builder.to_xml
    

    Will output:

    <?xml version="1.0"?>
    <root>
      <products>
        <widget>
          <id>10</id>
          <name>Awesome widget</name>
        </widget>
      </products>
    </root>
    

    Also, Ox does this too. Here's a sample from the documenation:

    require 'ox'
    
    doc = Ox::Document.new(:version => '1.0')
    
    top = Ox::Element.new('top')
    top[:name] = 'sample'
    doc << top
    
    mid = Ox::Element.new('middle')
    mid[:name] = 'second'
    top << mid
    
    bot = Ox::Element.new('bottom')
    bot[:name] = 'third'
    mid << bot
    
    xml = Ox.dump(doc)
    
    # xml =
    # <top name="sample">
    #   <middle name="second">
    #     <bottom name="third"/>
    #   </middle>
    # </top>