Question

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.

Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top