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>He开发者_开发技巧llo</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?
You need to wrap your fragment in a root element:
<div>
<h1>Hello</h1>
<p>Hi.</p>
</div>
should solve your problem.
精彩评论