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,
});

选项

选项类型默认值说明
spacesnumber | string0缩进(空格数或 "\t" 等字符串)
fullTagEmptyElementbooleanfalse空元素使用 <tag></tag> 而非 <tag/>
indentTextbooleanfalse文本节点按层级缩进
indentCdatabooleanfalseCDATA 节点按层级缩进
ignoreDeclarationbooleanfalse省略 XML 声明
ignoreCommentbooleanfalse省略注释
ignoreCdatabooleanfalse省略 CDATA 部分
ignoreDoctypebooleanfalse省略 DOCTYPE
ignoreTextbooleanfalse省略文本节点
attributeValueFnfunction自定义属性值处理器

格式化输出

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);
Copyright © 2026