我想使用 Ruby 中的 libxml读取一个包含超过一百万个小型书目记录(如)的大型XML文件。<article>...</article>
我已经尝试将 Reader 类与逐条读取记录的方法结合使用,expand
但我不确定这是正确的方法,因为我的代码会占用内存。因此,我正在寻找一种方法来方便地处理记录并使用恒定的内存。下面是我的主循环:
File.open('dblp.xml') do |io|
dblp = XML::Reader.io(io, :options => XML::Reader::SUBST_ENTITIES)
pubFactory = PubFactory.new
i = 0
while dblp.read do
case dblp.name
when 'article', 'inproceedings', 'book':
pub = pubFactory.create(dblp.expand)
i += 1
puts pub
pub = nil
$stderr.puts i if i % 10000 == 0
dblp.next
when 'proceedings','incollection', 'phdthesis', 'mastersthesis':
# ignore for now
dblp.next
else
# nothing
end
end
end
这里的关键是dblp.expand
读取整个子树(如<article>
记录)并将其作为参数传递给工厂以进行进一步处理。这是正确的方法吗?
然后,在工厂方法中,我使用类似于 XPath 的高级表达式来提取元素的内容,如下所示。再次,这可行吗?
def first(root, node)
x = root.find(node).first
x ? x.content : nil
end
pub.pages = first(node,'pages') # node contains expanded node from dblp.expand