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/>
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>

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