0

I have a large array of hashes like so:

[{:author=>"first,last", 
  :date=>"2014-07-02",
  :msg=>"some msg", 
  :paths=>[file1.ext, file2.ext]
  },
  {:author=>"first2,last2", 
   :date=>"2014-06-03", 
   :msg=>"some other msg", 
   :paths=>[file12.ext, file22.ext]
  },
  {.......}...
 ]

I can't seem to figure out how to create an XML file with the form below. Does anybody have any idea?

 <?xml version="1.0"?>
  <log>
  <logentry>
      <author>first, last</author>
      <date>YYYY-MM-DD</date>
      <paths>
        <path>path 1</path>
        <path>path n</path>
      </paths>
   </logentry>
   <logentry>
      <author>first2, last2</author>
      <date>YYYY-MM-DD</date>
      <paths>
        <path>path 1</path>
        <path>path n</path>
      </paths>
   </logentry>
   (and so forth)
  </log>
2
  • <author>'s nodeValue for the 2nd <logentry>.. first2, last2 ? Commented Jul 2, 2014 at 21:30
  • [SEE THIS POST][1], duplicate i guess. [1]: stackoverflow.com/questions/1739905/… Commented Jul 2, 2014 at 21:37

1 Answer 1

1

You can use builder. Documentation can be found here: https://github.com/jimweirich/builder

require 'builder'

def files_to_xml(files)
  xml = Builder::XmlMarkup.new(indent: 2)
  xml.instruct! :xml
  xml.log do |log|
    files.each do |file|
      log.logentry do |entry|
        entry.author file[:author]
        entry.date file[:date]
        entry.paths do |paths|
          file[:paths].each do |file_path|
            paths.path file_path
          end
        end
      end
    end
  end
end

files = [
  {
    :author=>"first,last", 
    :date=>"2014-07-02",
    :msg=>"some msg", 
    :paths=>['file1.ext', 'file2.ext']
  },
  {
    :author=>"first2,last2", 
    :date=>"2014-06-03", 
    :msg=>"some other msg", 
    :paths=>['file12.ext', 'file22.ext']
  }
]

puts files_to_xml(files)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.