pub struct DocxSaxReader<R: Read> { /* private fields */ }Expand description
基于 SAX 风格 XML 解析的流式 DOCX 读取器。
打开 .docx 文件(ZIP 归档),提取 word/document.xml,并使用 quick-xml
逐事件解析。每个块级元素转换为 DocumentEvent 并转发给提供的 EventSink。
内存使用量相对于文档大小为 O(1) – 仅当前正在解析的元素驻留在内存中。
类比 easyexcel-rust 的 XlsxSaxAnalyser。
§示例
use std::path::Path;
use easydoc_reader::extractor::sax::DocxSaxReader;
use easydoc_core::ContentCollector;
let mut reader = DocxSaxReader::from_path(Path::new("test.docx")).unwrap();
let mut collector = ContentCollector::new();
reader.read_events(&mut collector).unwrap();
let content = collector.into_content();Implementations§
Source§impl DocxSaxReader<Cursor<Vec<u8>>>
impl DocxSaxReader<Cursor<Vec<u8>>>
Sourcepub fn from_path(path: &Path) -> Result<Self>
pub fn from_path(path: &Path) -> Result<Self>
从文件路径创建读取器(使用默认安全策略)。
打开 .docx ZIP 归档,按默认 SecurityPolicy(ZIP 炸弹 / 元素爆炸防护)
验证,定位 word/document.xml 部分,并读入内存进行流式 XML 解析。
类比 easyexcel-rust 的 XlsxSaxAnalyser::new()。
§Errors
文件不存在、不是有效 ZIP、不包含 word/document.xml 或安全验证失败时返回错误。
Sourcepub fn from_path_with_security(
path: &Path,
security: SecurityPolicy,
) -> Result<Self>
pub fn from_path_with_security( path: &Path, security: SecurityPolicy, ) -> Result<Self>
Source§impl<R: Read> DocxSaxReader<R>
impl<R: Read> DocxSaxReader<R>
Sourcepub fn from_reader(source: R) -> Self
pub fn from_reader(source: R) -> Self
创建包装现有 Read 源(包含原始 XML)的读取器。
适用于测试场景或 XML 已被提取的情况。
Sourcepub fn read_events(&mut self, sink: &mut dyn EventSink) -> Result<()>
pub fn read_events(&mut self, sink: &mut dyn EventSink) -> Result<()>
流式遍历文档,将 DocumentEvent 推送给 sink。
开头发出 DocumentEvent::DocumentStart,结尾发出 DocumentEvent::DocumentEnd。
注意: DocumentBlock::Math 无法表示为 DocumentEvent,会被静默丢弃。
如需提取数学公式,请使用 read_blocks。
§Errors
XML 解析失败或 sink 返回错误时返回错误。
Sourcepub fn read_blocks(&mut self) -> Result<Vec<DocumentBlock>>
pub fn read_blocks(&mut self) -> Result<Vec<DocumentBlock>>
读取文档并按文档顺序返回所有块,包括 OMML 公式的 DocumentBlock::Math。
需要提取数学公式时推荐使用此入口。返回的块保留原始文档顺序: 段落、表格、图片和数学公式按与源 DOCX 相同的顺序出现。
Math 块的 omml 设置为原始 <m:oMath> 或 <m:oMathPara> XML,
latex 为 None,display 指示公式是块级(<m:oMathPara>)还是行内(<m:oMath>)。
§Errors
XML 解析失败时返回错误。