0

我有一个大型的本地 XML 文件(24 GB),其结构如下:

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

我需要这样的结果:

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

我想将 Nokigiri 与 SAX Parser 或 Reader 一起使用,因为我无法将整个文件加载到内存中。我正在使用 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 节点中的 URL。

如何在该代码中添加“每个都做”之类的内容来获取 URL 并获得如上所示的输出?或者是否可以在“字符”中调用多个动作?

4

1 回答 1

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
于 2013-02-07T11:32:49.507 回答