我有一个大型的本地 XML 文件(24 GB),其结构如下:
<id>****</id>
<url> ****</url> (several times within an id...)
我需要这样的结果:
id1;url1
id1;url2
id1;url3
id2;url4
....
我想将 Nokigiri 与 SAX Parser 或 Reader 一起使用,因为我无法将整个文件加载到内存中。我正在使用 Ruby Rake 任务来执行代码。
我的 SAX 代码是:
task :fetch_saxxml => :environment do
require 'nokogiri'
require 'open-uri'
class MyDocument < Nokogiri::XML::SAX::Document
attr_accessor :is_name
def initialize
@is_name = false
end
def start_element name, attributes = []
@is_name = name.eql?("id")
end
def characters string
string.strip!
if @is_name and !string.empty?
puts "ID: #{string}"
end
end
def end_document
puts "the document has ended"
end
end
parser = Nokogiri::XML::SAX::Parser.new(MyDocument.new)
parser.parse_file('/path_to_my_file.xml')
end
为了获取文件中的 ID,这很好,但我也需要获取每个 id 节点中的 URL。
如何在该代码中添加“每个都做”之类的内容来获取 URL 并获得如上所示的输出?或者是否可以在“字符”中调用多个动作?