Search code examples
xmlruby-on-rails-2

XML File not Neat


Please could anyone tell me the reason for this. I have a create_file action in my controller.

   file = File.new("xml/experiment.xml", "w") 
   # creating the builder file for the xml
   xml = Builder::XmlMarkup.new :target => file
   # xml tags 
   xml.instruct! 
   xml.EXPERIMENT_SET { 
   xml.alias("#{@experiment.alias}") 
   xml.center_name "#{@experiment.center_name}"
   } 

I get an output like this.

   <?xml version="1.0" encoding="UTF-8"?><EXPERIMENT_SET><alias>ZAP430</alias><center_name></center_name></EXPERIMENT_‌​SET>

Which is not a neat XML, all tags are displayed in a single line.


Solution

  • Use the parameter :indent while creating your instance of XmlMarkup.

    From the documentation of [Builder::XmlMarkup][1]:

    xm = Builder.new(:indent=>2)
    # xm will produce nicely formatted and indented XML.
    
    xm = Builder.new(:indent=>2, :margin=>4)
    # xm will produce nicely formatted and indented XML with 2
    # spaces per indent and an over all indentation level of 4.
    
    builder = Builder::XmlMarkup.new(:target=>$stdout, :indent=>2)
    builder.name { |b| b.first("Jim"); b.last("Weirich) }
    # prints:
    #     <name>
    #       <first>Jim</first>
    #       <last>Weirich</last>
    #     </name>