【问题标题】:Reading xml files after unzipping using rubyzip使用rubyzip解压后读取xml文件
【发布时间】:2012-07-06 10:09:42
【问题描述】:
 require 'active_support/core_ext'
 require 'open-uri'
 require 'zip/zip'


 zipfilename = open(url which returns a zip file with no of xml files inside)
 Zip::ZipFile.open(zipfilename) do |zipfile|
   zipfile.each do |entry|  
    xml = File.open(entry).read
    xml_to_hash = Hash.from_xml(xml)
   end
end

当我尝试打印变量条目时,它以 file_name.xml 的形式出现。错误来自 xml = File.open(entry).read。

错误:

test.rb:51:in `initialize': can't convert Zip::ZipEntry into String (TypeError)
from test.rb:51:in `open'
from test.rb:51:in `block (2 levels) in <main>'

【问题讨论】:

    标签: ruby-on-rails ruby zip rubyzip


    【解决方案1】:

    而不是

    xml = File.open(entry).read
    

    试试

    xml = zipfile.read(entry)
    

    【讨论】:

      【解决方案2】:

      您正在迭代的entry 不是真正的文件。它只是代表档案中的一个文件。我认为您需要将 Zip::ZipEntry 类型的条目转换为可以阅读的内容。

      查看http://rubyzip.sourceforge.net/classes/Zip/ZipFile.html的示例

      据我所知,您可以通过调用 get_input_stream 或直接调用 read: http://rubyzip.sourceforge.net/classes/Zip/ZipEntry.html#M000135 来获得类似 io 的对象

      【讨论】:

      • 谢谢。我使用 get_input_stream 来获取数据。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多