【发布时间】:2011-11-21 13:10:54
【问题描述】:
我有一个小问题。 我需要将大型 xml 文件(每个 1-4GB)转换为 CSV。 我知道我可以使用 Nokogiri 的 SAX 解析器来做到这一点,但我被卡住了。
<Documents>
<Document DocID="10170306" DocType="Message">
<FieldValues>
<E03>-1166737392</E03>
<E05>petrosky (petrosky@foo.com)</E05>
<E06>00000000B89476181EE6C34FB4E9D87F9E44A85944002000</E06>
<E07>\foo-dedup-global.mbox_99.mbox\</E07>
<E08>5/12/2011 6:32:38 PM</E08>
<E09>Fwd: important decision for v1 launch</E09>
<E10>Susan Infantino (susani@foo.com); Mike Yang (foo@mail.com)</E10>
<F01>Jun 8 2011 7:43AM</F01>
<F02>May 12 2011 6:32PM</F02>
<F03>Msg0002_important decisi.html</F03>
<F04>MSMAIL</F04>
<F05>CA4DBB95C638FB656CB02627DDEA90C9</F05>
<F06>28677</F06>
<F07>foo-dedup-global.mbox_99.mbox.pst</F07>
<F08>10164846</F08>
<F09>10170306</F09>
<E11>0</E11>
<E12><BANLkTi=yztN5Pd0v9i9+zN=aYhAo5Y8ffA@mail.foo.com></E12>
</FieldValues>
<Files>
<File FileType="Native">
<ExternalFile FilePath="\04_EXT\31\foo-dedup-global.mbox_99.mbox.pst10164846.dir\foo-dedup-global.mbox_99.mbox\" FileName="Msg0002_important decisi.html" FileSize="28677" Hash="CA4DBB95C638FB656CB02627DDEA90C9" HashType="MD5" />
</File>
</Files>
<Locations>
<Location>
<Custodian>Yang_Mike</Custodian>
<LocationURI>\\ANNATXCIFS02\PN_Dunbar_F01401\04_EXT\31\foo-dedup-global.mbox_99.mbox.pst10164846.dir\foo-dedup-global.mbox_99.mbox\Msg0002_important decisi.html</LocationURI>
</Location>
</Locations>
</Document>
</Documents>
我玩了一下事件驱动编程。
require 'fileutils'
require 'faster_csv'
require 'nokogiri'
file = ARGV[0]
include Nokogiri
class Xmlfile < XML::SAX::Document
def start_element name, attrs
# Process data here
if name == 'Document'
documentName = [*attrs]
puts documentName
end
if name == 'File'
file = [*attrs]
puts file
end
if name == 'ExternalFile'
externalFile = [*attrs]
puts externalFile
end
end
# def end_element name, attrs
# end
end
parser = XML::SAX::Parser.new(Xmlfile.new)
parser.parse_file(file)
【问题讨论】:
-
问题/问题到底是什么?上面的代码有效,即它输出所有
Document、File和ExternalFile节点的所有属性。 -
@undur_gongor 他想将其转换为 CSV,它在标题中。
-
请附上您将如何将部分 xml 文件映射到 csv 列。