作者:天边的云YEAH_988 | 来源:互联网 | 2023-09-14 20:25
我有一个 30MB 的 XML 文件,开头包含一些乱码,因此通常我必须删除它,以便 Nokogiri 能够正确解析 XML 文档。
这是我目前拥有的:
cOntents= File.open(file_path).read
if contents[0..123].include? 'authenticate_response'
fixed_cOntents= File.open(file_path).read[123..-1]
File.open(file_path, 'w') { |f| f.write(fixed_contents) }
end
但是,这实际上会导致 ruby 脚本两次打开大型 XML 文件。一次读取前 123 个字符,另一次读取除前 123 个字符以外的所有字符。
为了解决第一个问题,我能够做到这一点:
cOntents= File.open(file_path).read(123)
但是,现在我需要从文件中删除这些字符而不读取整个文件。如何“修剪”该文件的开头而不必在内存中打开整个文件?
回答
你可以打开文件一次,然后读取并检查“垃圾”,最后将打开的文件直接传递给 nokogiri 进行解析。这样,您只需要读取一次文件而根本不需要写入它。
File.open(file_path) do |xml_file|
if xml_file.read(123).include? 'authenticate_response'
# header found, nothing to do
else
# no header found. We rewind and let nokogiri parse the whole file
xml_file.rewind
end
xml = Nokogiri::XML.parse(xml_file)
# Now to whatever you want with the parsed XML document
end
请参阅的文件IO#read
,IO#rewind
以及Nokigiri::XML::Document.parse
关于这些方法的细节。
I updated the answer to use the block variant of `File.open`. However, even without this, the file would be implicitly closed on next garbage collection.