0

我有一个 CSV,我喜欢在上面保存我所有的哈希值。我正在使用 nokogiri sax 解析 xml 文档,然后将其保存到 CSV。

它解析并保存第一个 xml 文件,但是当开始解析第二个文件时,它停止并且我得到的错误是:

错误: NoMethodError: undefined method <<' for nil:NilClass`

@infodata[:titles] << @content 中发生 nil 错误

萨克斯解析器:

require 'rubygems'
require 'nokogiri'
require 'csv'

class MyDocument < Nokogiri::XML::SAX::Document

  HEADERS = [ :titles, :identifier, :typeOfLevel, :typeOfResponsibleBody, 
              :type, :exact, :degree, :academic, :code, :text ]

  def initialize
     @infodata = {}
     @infodata[:titles] = Array.new([])
  end

  def start_element(name, attrs)
    @attrs = attrs
    @content = ''
  end
  def end_element(name)
    if name == 'title'
      Hash[@attrs]["xml:lang"]
      @infodata[:titles] << @content
      @content = nil
    end
    if name == 'identifier'
       @infodata[:identifier] = @content
       @content = nil
    end
    if name == 'typeOfLevel'
       @infodata[:typeOfLevel] = @content
       @content = nil
    end
    if name == 'typeOfResponsibleBody'
       @infodata[:typeOfResponsibleBody] = @content
       @content = nil
    end
    if name == 'type'
       @infodata[:type] = @content
       @content = nil
    end
    if name == 'exact'     
       @infodata[:exact] = @content
       @content = nil
    end
    if name == 'degree'
       @infodata[:degree] = @content
       @content = nil
    end
    if name == 'academic'
       @infodata[:academic] = @content
       @content = nil
    end
    if name == 'code'
       Hash[@attrs]['source="vhs"']
       @infodata[:code] = @content 
       @content = nil
    end
    if name == 'ct:text'
       @infodata[:beskrivning] = @content
       @content = nil
    end 
  end
  def characters(string)
    @content << string if @content
  end
  def cdata_block(string)
    characters(string)
  end
  def end_document
    File.open("infodata.csv", "ab") do |f|
      csv = CSV.generate_line(HEADERS.map {|h| @infodata[h] })
      csv << "\n"
      f.write(csv)
    end
  end
end

为存储在文件夹中的每个文件(47.000xml 文件)创建新对象:

parser = Nokogiri::XML::SAX::Parser.new(MyDocument.new)
counter = 0

Dir.glob('/Users/macbookpro/Desktop/sax/info_xml/*.xml') do |item|
  parser.parse(File.open(item, 'rb'))
  counter += 1
  puts "Writing file nr: #{counter}"
end

3个用于尝试代码的xml文件:https: //gist.github.com/2378898 https://gist.github.com/2378901 https://gist.github.com/2378904

4

1 回答 1

0

你正在这样做:

csv = CSV.generate_line(HEADERS.map {|h| @infodata[h] })
csv << "\n"

如果由于某种原因CSV.generate_line(HEADERS.map {|h| @infodata[h] })返回nil,您将尝试对未定义的 nil 对象使用 << 方法。

您可能需要添加一些条件以避免将“\n”添加到csv(如果它为 nil)。

于 2012-04-14T22:26:53.187 回答