Domanda

Ho questo codice.

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

eseguito su un frammento di HTML come questo,

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

l'output mostra che solo il primo elemento viene elaborato:

start_element h1
characters Hello
end_element h1

Se io avvolgere il frammento in html e body tag, il tutto in ingresso viene analizzato.

C'è un modo per utilizzare un parser stile SAX su frammenti HTML?

È stato utile?

Soluzione

È necessario avvolgere il frammento in un elemento radice:

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

dovrebbe risolvere il tuo problema.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top