【问题标题】:Using SAX Parser to get several sub-nodes?使用 SAX Parser 获取多个子节点?
【发布时间】:2023-03-10 11:38:01
【问题描述】:

我有一个大型的本地 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 并获得如上所示的输出?或者是否可以在“字符”中调用多个动作?

【问题讨论】:

    标签: ruby-on-rails ruby nokogiri sax saxparser


    【解决方案1】:

    其实这是一个在多个节点出现时解析它们的解决方案。 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
    

    【讨论】:

    • 我有一个问题,SAX 解析器对于大型 xmls(GBs) 是否很快?你的文件进展如何?
    猜你喜欢
    • 2020-03-08
    • 2012-05-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 2012-01-28
    • 2017-09-10
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多