views:

172

answers:

1

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.

+1  A: 

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 ;-)

jldupont
Thank you very much quick response. Yes,your proposal is sensible. I found http://stackoverflow.com/questions/1020409/dom4j-saxreader-stop-parsing that entry before asked in here. It is also same your idea. I will use exception for stop parse... Also try to more see docs too. Thanks jldupont.
tknv