简体   繁体   English

使用ruby从CSV生成XML

[英]Generate XML out of CSV using ruby

I have a CSV file which I want to parse with ruby and generate a XML out of it. 我有一个CSV文件,我想用ruby解析并从中生成XML。

Here's a sample CSV: 这是一个示例CSV:

id;us;de
1;hello;hallo
2;usa;deutschland
3;big;gross

The XML should look like this when it's done: 完成后,XML应如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <cat id="1">
        <attrs>
            <attr attr-id="word" xml:lang="us">hello</attr>
            <attr attr-id="word" xml:lang="de">hallo</attr>
        </attrs>
    </cat>
    <cat id="2">
        <attrs>
            <attr attr-id="word" xml:lang="us">usa</attr>
            <attr attr-id="word" xml:lang="de">deutschland</attr>
        </attrs>
    </cat>
    <cat id="3">
        <attrs>
            <attr attr-id="word" xml:lang="us">big</attr>
            <attr attr-id="word" xml:lang="de">gross</attr>
        </attrs>
    </cat>
</catalog>

And here's what my ruby file looks like so far: 到目前为止,这是我的ruby文件的外观:

require 'csv'

file = File.open("file.csv", "r:UTF-8").read

data = CSV.parse(file, :quote_char => "'", :col_sep => ";")

data.each do |column|  
    id = column[0]
    puts id
end

I get each column but I can't loop through it to generate the XML. 我得到了每一列,但无法遍历它来生成XML。 Do you have any idea how to get to my final XML? 您是否知道如何获取最终的XML?

require 'csv'

puts '<?xml version="1.0" encoding="UTF-8"?>'

CSV.foreach("data.csv") do |row|
  puts '<catalog>'
  puts '<cat id=' + "#{row[0]}" + '>'
  puts '<attrs>'
  puts '<attr attr-id="word" xml:lang=' + "#{row[1]}" +'>hello</attr>'
  puts '<attr attr-id="word" xml:lang=' + "#{row[2]}" +'>hello</attr>'
  puts '</attrs>'
  puts '</cat>'
end

puts '</catalog>'

For a more general case: 对于更一般的情况:

require 'nokogiri'
require 'csv'

builder = Nokogiri::XML::Builder.new do |xml|
  xml.items {
    CSV.foreach 'items.csv', headers: true do |row|
      xml.item {
        row.headers.each do |key|
          xml.send key, row[key]
        end
      }
    end
  }
end

File.open('items.xml', 'w'){|f| f << builder.to_xml}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM