2013-02-02 44 views
0

我有這樣一個結構的大本地XML文件(24 GB):使用SAX解析器獲取多個子節點?

<id>****</id> 
<url> ****</url> (several times within an id...) 

我需要這樣一個結果:

id1;url1 
id1;url2 
id1;url3 
id2;url4 
.... 

我想用Nokigiri或者與SAX解析器或閱讀器,因爲我無法將整個文件加載到內存中。我正在使用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節點中的網址了。

我該如何在代碼中放入類似「each do」的內容來獲取URL並獲得如上所示的輸出?或者是否可以在「角色」中調用多個動作?

回答

0

實際上,這是解決幾個節點發生時的解決方案。 SAX解析器的問題在於你必須找到一種處理特殊字符的方法,比如「&」等......但這是另一回事。

這裏是我的代碼:

class MyDoc < Nokogiri::XML::SAX::Document 
    def start_element name, attrs = [] 
    @inside_content = true if name == 'yourvalue' 
    @current_element = name 
    end 


    def characters str 

    if @current_element == 'your_1st subnode' 

    elsif @current_element == 'your 2nd subnode' 


    end 
    puts "#{@current_element} - #{str}" if @inside_content && %w{your_subnodes here}.include?(@current_element) 
    end 

    def end_element name 
    @inside_content = false if name == 'yourvalue' 
    @current_element = nil 
    end 

end 

parser = Nokogiri::XML::SAX::Parser.new(MyDoc.new) 
parser.parse_file('/path_to_your.xml') 

end 
+0

我有問題,就是SAX解析器是快大個XML(GBS)?它是如何進展你的文件? –