2011-11-21 69 views
1

我有一點問題。 我需要將大型XML文件(每個1-4GB)轉換爲CSV。 我知道我可以用Nokogiri的SAX解析器做到這一點,但我被卡住了。Ruby:將大的.xml文件轉換爲csv

<Documents> 
    <Document DocID="10170306" DocType="Message"> 
    <FieldValues> 

     <E03>-1166737392</E03> 
     <E05>petrosky ([email protected])</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 ([email protected]); Mike Yang ([email protected])</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>&lt;[email protected]&gt;</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) 
+2

究竟有什麼問題/問題?上面的代碼工作,即輸出所有'Document','File'和'ExternalFile'節點的所有屬性。 –

+0

@undur_gongor他想將其轉換爲CSV,它在標題中。 –

+1

請附上你如何將你的xml文件的一部分映射到csv列。 – WarHog

回答

3

它看起來就像你在你的puts輸出你需要的信息,並試圖將數據捕捉到的變量。您錯過了將變量發送到CSV生成器的部分。

您可以將documentName,fileexternalFile附加到數組並將其傳遞給CSV。

CSV documentation顯示了幾種很好的方式來生成輸出。查看「寫作」部分以獲取更多信息。

從文檔:

FasterCSV.open("path/to/file.csv", "w") do |csv| 
    csv << ["row", "of", "CSV", "data"] 
    csv << ["another", "row"] 
    # ... 
end 
+0

以下是CSV的標準庫文檔:http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html – Phrogz

+0

如何動態地將xml添加到使用Ruby的CSV中?我已經可以寫入CSV了,但它只會將數據輸入到一行中 - 因此迭代它會不斷被覆蓋。 –

+0

您需要將您的問題作爲新問題提出,而不是作爲對答案的評論。我們沒有任何可能的方式來回答你我們對你的情況瞭解甚少。 –