CORE
Formatter
将 XmlComponent 树转换为可序列化的 XML 对象和字符串
Formatter 将 XmlComponent 树转换为普通对象或 XML 字符串。Packer 在内部使用它来序列化文档。
基本用法
import { Formatter, XmlComponent } from "@office-open/core";
const formatter = new Formatter();
const component = new XmlComponent("w:p");
const context = { stack: [], file: {} };
const xmlObj = formatter.format(component, context);
// 返回 IXmlableObject — 普通对象表示
format()
将 XmlComponent 树转换为 IXmlableObject — 可进一步处理的普通 JavaScript 对象:
const xmlObj = formatter.format(component, context);
返回的对象遵循 xml-js Element 结构,包含 name、attributes 和 elements 字段。
formatToXml()
将 XmlComponent 树直接转换为 XML 字符串:
const xml = formatter.formatToXml(component, context);
// '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<w:p/>'
const xmlNoDecl = formatter.formatToXml(component, context, false);
// '<w:p/>'
第三个参数控制是否包含 XML 声明。
Context
IContext 对象在格式化过程中传递给组件树:
interface IContext<TFileData = {}> {
stack: BaseXmlComponent[];
file: TFileData;
}
stack— 跟踪当前组件层次结构file— 携带文件级数据(媒体、关系等)
何时使用
通常不需要直接使用 Formatter。Packer 会自动处理序列化。在以下场景使用 Formatter:
- 检查组件树的 XML 输出
- 构建自定义导出流程
- 调试组件结构