Question

I have this code.

class MyParser < Nokogiri::XML::SAX::Document
  def characters(string)
    LOG.debug("characters #{string}")
  end

  def start_element(name, attrs = [])
    LOG.debug("start_element #{name}")
  end

  def end_element(name)
    LOG.debug("end_element #{name}")
  end
end

parser = Nokogiri::HTML::SAX::Parser.new(MyParser.new)
parser.parse(File.new($*[0], 'rb'))

Run on an HTML fragment like this,

<h1>Hello</h1> 
<p>Hi.</p>

the output shows that only the first element is processed:

start_element h1
characters Hello
end_element h1

If I wrap the fragment in html and body tags, the whole input is parsed.

Is there a way to use a SAX style parser on HTML fragments?

Was it helpful?

Solution

You need to wrap your fragment in a root element:

<div>
<h1>Hello</h1> 
<p>Hi.</p>
</div>

should solve your problem.

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