如何从带有哈希的数组构建XML?

时间:2014-07-02 21:18:04

标签: ruby xml

我有大量的哈希像这样:

[{: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]
  },
  {.......}...
 ]

我似乎无法弄清楚如何使用下面的表单创建XML文件。有人有任何想法吗?

 <?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>

1 个答案:

答案 0 :(得分:1)

您可以使用构建器。可以在此处找到文档: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)