如何在 'Ox' gem 的帮助下从 ruby 中的 html 标记中提取纯文本

How to extract plain text from html markup in ruby with help of 'Ox' gem

我在数据库 table 文本字段中存储了很多标记,这些标记可以有不同的结构。 我需要从存储在数据库中的这些标记片段中提取纯文本,所以我决定为此使用 Ox gem 因为它是 [=23] 最快的 xml 解析库=] 根据测试。当我尝试这样做时,我得到这样的错误:

irb(main):026:0> Ox.parse(some_html)
Ox::ParseError: invalid format, document not terminated at line 1, column 23 [parse.c:521]

我知道如何使用 Nokogiri 但我需要使用 Ox

对于解析 html 我应该使用带有 sax 处理程序的 Ox.sax_html 方法,而不是 Ox.parse

require 'stringio'
require 'ox'

class TextHandler < ::Ox::Sax
  attr_reader :parsed_text

  def initialize()
    @parsed_text = ''
  end

  def text(value)
    @parsed_text << " #{value}"
  end
end

text_handler = TextHandler.new

options = {
  symbolize: true,
  skip: :skip_white,
  smart: true
}

some_markup = '<img src="logo.png" alt="logo"><div>hello</div><div>world ...'

input = StringIO.new(some_markup)

Ox.sax_html(text_handler, input, options)

text_handler.parsed_text