XML
序列化
将 Element 树转换回 XML 字符串,支持格式化选项
基本序列化
import { parse, stringify } from "@office-open/xml";
const root = parse("<w:p><w:r><w:t>Hello</w:t></w:r></w:p>");
const xml = stringify(root);
// '<w:p><w:r><w:t>Hello</w:t></w:r></w:p>'
stringify(root, options?)
const xml = stringify(root, {
spaces: 2,
ignoreDeclaration: true,
});
选项
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
spaces | number | string | 0 | 缩进(空格数或 "\t" 等字符串) |
fullTagEmptyElement | boolean | false | 空元素使用 <tag></tag> 而非 <tag/> |
indentText | boolean | false | 文本节点按层级缩进 |
indentCdata | boolean | false | CDATA 节点按层级缩进 |
ignoreDeclaration | boolean | false | 省略 XML 声明 |
ignoreComment | boolean | false | 省略注释 |
ignoreCdata | boolean | false | 省略 CDATA 部分 |
ignoreDoctype | boolean | false | 省略 DOCTYPE |
ignoreText | boolean | false | 省略文本节点 |
attributeValueFn | function | — | 自定义属性值处理器 |
格式化输出
const xml = stringify(root, { spaces: 2 });
// <w:p>
// <w:r>
// <w:t>Hello</w:t>
// </w:r>
// </w:p>
往返示例
解析 XML 字符串,修改树结构,再序列化回去:
import { parse, stringify, findChild, children } from "@office-open/xml";
const root = parse("<w:p><w:r><w:t>Hello</w:t></w:r></w:p>");
const runs = children(root, "w:r");
// ... 修改树结构 ...
const output = stringify(root);