Search code examples
rubyhashxml-parsingxml-simple

How do I parse a hash to XML using XmlSimple?


I have a hash that i wanted to parse to XML using SimpleXML but there is a trick I dont know how to handle:

My hash looks like:

require 'xmlsimple'
test = { "subroot" => {
  field1 => {'var1' = ['xyz'], 'var2' = ['yyyy']},
  field2 => {'var1' = ['xyz'], 'var2' = ['yyyy']},
  field3 => {'var1' = ['xyz'], 'var2' = ['yyyy']}, 
  'id' = 'xxxxxx'} }

I parse it to XML using:

XmlSimple.xml_out(teste, 'RootName' => 'root') 

resulting in:

<cenario>
  <subroot id="xxxxxx">
     <field1>
       <var1>xyz</var1>
       <var2>yyyy</var2>
     </field1>
     <field2>
       <var1>xyz</var1>
       <var2>yyyy</var2>
     </field2>
     <field3>
       <var1>xyz</var1>
       <var2>yyyy</var2>
     </field3>
   </subroot>
</cenario>

That's OK and works like a charm but there is problem when I need to loop. Im doing a automated test that loops on each test and save the test data on a Hash and by the end of the tests i need to save it on a xml and i need to get something like this:

<cenario>
      <subroot id="xxxxxx">
         <field1>
           <var1>xyz</var1>
           <var2>yyyy</var2>
         </field1>
         <field2>
           <var1>xyz</var1>
           <var2>yyyy</var2>
         </field2>
         <field3>
           <var1>xyz</var1>
           <var2>yyyy</var2>
         </field3>
       </subroot>
      .
      .
      .
      <subroot id="xxxx10x">
         <field1>
           <var1>xyz</var1>
           <var2>yyyy</var2>
         </field1>
         <field2>
           <var1>xyz</var1>
           <var2>yyyy</var2>
         </field2>
         <field3>
           <var1>xyz</var1>
           <var2>yyyy</var2>
         </field3>
       </subroot>
    </cenario>

merging each hash on each test will not do the trick cz it prevents the last hash (subroot) Did i made myself clear? Can't simpleXML do the trick or do I need to look for another solution?


Solution

  • Thks for the help...

    I figured out that i dont need Hash keys if i put a "instance" of the hash inside a array... I can use the same Hash name, each array slot saves a instance of my hash than i can call simpleXML or to_xml

    No i just need to figure out how to remove the objects tags that makes the xml bigger.