Class: XlsxKit::SAXParser

Inherits:
Object
  • Object
show all
Defined in:
lib/xlsxkit/sax_parser.rb

Overview

轻量 SAX 风格 XML 解析器,专为 XLSX 内部 XML 流式处理设计。

与 XmlUtils::TreeParser(DOM 全量建树)不同,本解析器不在内存中构建节点树, 而是逐标签触发回调(start_element / end_element / characters),内存占用恒定。

核心算法:增量缓冲 — 每次从 IO 读取一块数据追加到 @buf, 尝试提取已完整的标签/文本段并回调,不完整的尾部保留到下次。 这样即使数百 MB 的 sheet XML 也只占用几十 KB 内存。

Handler 协议(鸭子类型,无需继承): start_element(name, attrs) — 遇到开始标签 end_element(name) — 遇到结束标签 characters(text) — 遇到文本内容(可能分多次回调)

Constant Summary collapse

BUFFER_SIZE =

64KB 读取块

65536

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, handler) ⇒ SAXParser

Returns a new instance of SAXParser.



43
44
45
46
47
48
49
# File 'lib/xlsxkit/sax_parser.rb', line 43

def initialize(source, handler)
  @source  = source
  @handler = handler
  @buf     = ''.b
  @eof     = false
  @i       = 0  # 已消费位置
end

Class Method Details

.parse(source, handler) ⇒ Object



39
40
41
# File 'lib/xlsxkit/sax_parser.rb', line 39

def self.parse(source, handler)
  new(source, handler).parse
end

Instance Method Details

#parse ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/xlsxkit/sax_parser.rb', line 51

def parse
  until @eof && @i >= @buf.length
    fill_buffer if !@eof && (@buf.length - @i) < BUFFER_SIZE
    step || (@eof = true)
  end
  # 尾部残余文本
  if @i < @buf.length
    text = @buf[@i..]
    emit_text(text) unless text.strip.empty?
  end
end