Can Nokogiri use the SAX parser to parse an HTML fragment?

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 snippet 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 complete the snippet in htmland tags body, all input is parsed.

Can I use the SAX parser for HTML snippets?

+3
source share
1 answer

You need to wrap the fragment in the root element:

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

should solve your problem.

+2
source

Source: https://habr.com/ru/post/1737088/


All Articles