Volodymyr Hnatiuk Volodymyr Hnatiuk - 23 days ago 6
Ruby Question

Write array to xml Ruby

I need to generate simple file with test results with the next fields:

Total N
Pass N
Fail N

Failed: testName1
...
Failed: testNameN


I use Nokogiri to write xml file.
For first 3 fields I have the next code:

xml = Nokogiri::XML::Builder.new { |xml|
xml.body do
xml.Total total
xml.Pass pass
xml.Fail fail
end
}.to_xml


I have array with failed test names. And I need iterate thought that array and write each failed test name to this xml file, using nokogiri. How is to do that?
I want something like this:

<failed> testname1 </failed>
<failed> testname2 </failed>
<failed> testnameN </failed>

Answer

A few notes :

fail is a synonym for raise, and shouldn't be used as a variable name.

It might cause confusion if you use xml for both the String from your Nokogiri::XML::Builder and for the bound variable used inside the Builder block.

require 'nokogiri'

total = 5
pass_count = 3
fail_count = 2

failed_tests = ["test_name_1", "test_name_3"]

xml_content = Nokogiri::XML::Builder.new { |xml| 
  xml.body do
    xml.Total total
    xml.Pass pass_count
    xml.Fail fail_count

    xml.failed do
      failed_tests.each do |failed_test|
        xml.failed failed_test
      end
    end

  end
}.to_xml

puts xml_content

# <?xml version="1.0"?>
# <body>
#  <Total>5</Total>
#  <Pass>3</Pass>
#  <Fail>2</Fail>
#  <failed>
#    <failed>test_name_1</failed>
#    <failed>test_name_3</failed>
#  </failed>
# </body>