xmlsaxlibxml-ruby

How can I stop parse when find the 1st element?


I would like to stop parse when find 1st element even there is more same element after that. I use libxml,SAX on ruby.
This code show every <usr> element.
But I want to stop parse when find 1st <usr>.
Because this XML file will be huge. Does anybody know how stop to parse when find 1st element by SAX method.

code

#! ruby -Ku

require 'rubygems'
require 'libxml'
include LibXML

class PostCallbacks
  include XML::SaxParser::Callbacks

  def on_start_element(element, attributes)
    if /usr/ =~ element
      p element
    end
  end
  
end

parser = XML::SaxParser.file('test.xml')
parser.callbacks = PostCallbacks.new
parser.parse

Thanks.


Solution

  • I don't know if this is also applicable under Ruby but for the Python SAX module, one must throw an exception to get out of the "parse" phase... it is the only way to do it without hacking.

    I guess if you didn't find a method in the Ruby documentation, that probably means my proposal is sensible ;-)