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/> |
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>
js2xml
为了 xml-js 兼容性,js2xml 作为别名可用:
import { js2xml } from "@office-open/xml";
const xml = js2xml(element);
xml(node-xml 格式)
xml 函数将 XmlObject(node-xml 格式)直接转换为 XML:
import { xml } from "@office-open/xml";
const xmlString = xml(
{
"w:p": [{ "w:r": [{ "w:t": ["Hello"] }] }],
},
{ indent: 2 },
);
这比经过 Element 中间格式更高效。
往返示例
解析 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);