Ruby:将XML解析为CSV

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ruby:将XML解析为CSV相关的知识,希望对你有一定的参考价值。

I had an XML file that I needed to convert to CSV. In order to make things easier for myself, I used a pipe | symbol instead of a comma so that there would be no parsing errors later. I also ended up writing the file to a Txt file and importing it as such to Microsoft Excel.
  1. require 'rexml/document'
  2.  
  3. xml_file = File.open("showcase.xml", "r")
  4. csv_file = File.new("showcase.txt", "w")
  5.  
  6. xml = REXML::Document.new( xml_file )
  7.  
  8. counter = 0
  9. xml.elements.each("images") do |e|
  10. e.elements.each("image") do |f|
  11. counter = counter + 1
  12.  
  13. csv_file.puts f.elements['src'].text + "|" + f.elements['caption'].text + "|" + f.elements['uri'].text + "|"
  14. end
  15. end

以上是关于Ruby:将XML解析为CSV的主要内容,如果未能解决你的问题,请参考以下文章

使用 powershell 将嵌套的复杂 XML 解析为 CSV

Python将XML解析为缺少元素的CSV

将 XML 文件中的所有元素解析为 CSV,无需硬编码值

Ruby/Rails CSV 解析,UTF-8 中的无效字节序列

某些行的 XML 文件解析错误 [关闭]

使用 XSLT 将 XML 转换为 CSV