跳到主要内容
Office Open

XML

解析

将 XML 字符串解析为 Element 树,支持可配置选项

#基本解析

ts
import { parse } from "@office-open/xml";

const root = parse(`<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:r><w:t>Hello</w:t></w:r>
</w:p>`);

// root.name === "w:p"
// root.elements[0].name === "w:r"

parse 函数将 XML 字符串转换为 Element 树。

#parse(xml, options?)

ts
const root = parse(xmlString, {
  trim: true,
  ignoreComment: true,
});

#选项

选项类型默认值说明
trimbooleanfalse去除文本节点中的空白
captureSpacesBetweenElementsbooleanfalse保留元素间的纯空白文本节点
ignoreDeclarationbooleanfalse跳过 XML 声明(<?xml ...?>)
ignoreCommentbooleanfalse跳过 XML 注释(<!-- -->)
ignoreCdatabooleanfalse跳过 CDATA 部分
ignoreDoctypebooleanfalse跳过 DOCTYPE 声明
ignoreTextbooleanfalse跳过文本节点
nativeTypeAttributesbooleanfalse将属性值转换为原生类型

#Element 结构

每个解析后的节点是一个 Element 对象——完整接口见类型参考。元素通常使用 name、attributes 和 elements:

ts
interface Element {
  type?: string;
  name?: string;
  attributes?: Attributes;
  elements?: Element[];
  text?: string | number | boolean;
  // ... 以及 cdata、comment、declaration 等
}

文本内容存于元素的 text 字段,而非独立节点:

ts
// 解析 <w:t>Hello World</w:t>
{ type: "element", name: "w:t", text: "Hello World" }

#命名空间处理

命名空间作为普通属性保留:

ts
const root = parse(`<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:r><w:t>Hello</w:t></w:r>
</w:p>`);

// root.attributes["xmlns:w"] === "http://schemas.openxmlformats.org/..."

所有元素名称包含前缀,因此查询时使用 "w:p"、"w:r" 等。

#从 ZIP 归档中读取

结合 @office-open/core 从 OOXML 文件中解析 XML:

ts
import { readFileSync } from "node:fs";
import { parseArchive } from "@office-open/core";

const archive = parseArchive(readFileSync("document.docx"));
const document = archive.get("word/document.xml");
// document 已经是 Element 树