2014-01-15 4 views
0

압축을 풀고 구문 분석해야하는 외부 xml 파일 다운로드가 있습니다. 나는 그것을 다운로드하고 압축을 풀었지만 지금은 Zip :: Entry 객체로 붙어 있으며 Nokogiri와 구문 분석 할 수 없다.XML 파일을 압축 해제 한 후 Zip :: Entry 개체 읽기

require 'open-uri' 
require 'zip' 
require 'nokogiri' 

url = 'https://download.api.bingads.microsoft.com/ReportDownload/Download.aspx?xmlfile' 
zip_file = open(url) 
# file pulled down successfully => tmp/localpath 

unzippedxml = Zip::File.open(zip_file.path) do |z| 
    xml_file = z.first 
end 
#output is my xml file => myxml.xml 

unzippedxml.class => Zip::Entry 

Nokogiri::XML("unzippedxml") 
=> #<Nokogiri::XML::Document:0x212b2c0 name="document") 

이 파일을 어떻게 분석합니까? 나는 압축을 풀 필요가없는 더미 XML 파일을 만들었고 콘솔에서 파싱 할 수 있었지만이 파일을 열 수는 없습니다.

도움이 될 것입니다.

답변

1

Zip::ZipFile은 전체 Zip 컨테이너를 나타냅니다. 대신이 컨테이너 안에는 클래스 Zip::ZipEntry의 객체가 필요합니다. 당신은 예를 들어 특정 이름을 가진 파일을 얻을 수 Zip::ZipFile.read을 사용할 수

require 'zip/zip' 

zip = Zip::ZipFile.open('some.zip')     # open zip 
xml_source = zip.read('filename_inside_zip.xml') # read file contents 

# now use the contents of xml_source with Nokogiri 

을 또는, 당신은 이름을 모르는 경우하지만 우편에 하나 개의 파일이 항상 거기, 당신은 단지 첫 번째를 취할 수 있습니다 :

require 'zip/zip' 

zip = Zip::ZipFile.open('some.zip')     # open zip 
entry = zip.entries.reject(&:directory?).first  # take first non-directory 
xml_source = entry.get_input_stream{|is| is.read } # read file contents 

# now use the contents of xml_source with Nokogiri