XML

序列化

将 Element 树转换回 XML 字符串,支持格式化选项

基本序列化

import { xml2js, js2xml } from "@office-open/xml";

const root = xml2js("<w:p><w:r><w:t>Hello</w:t></w:r></w:p>");
const xml = js2xml(root);
// '<w:p><w:r><w:t>Hello</w:t></w:r></w:p>'

js2xml(root, options?)

const xml = js2xml(root, {
  spaces: 2,
  ignoreDeclaration: true,
});

选项

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

格式化输出

const xml = js2xml(root, { spaces: 2 });
// <w:p>
//   <w:r>
//     <w:t>Hello</w:t>
//   </w:r>
// </w:p>

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 { xml2js, js2xml, findChild, children } from "@office-open/xml";

const root = xml2js("<w:p><w:r><w:t>Hello</w:t></w:r></w:p>");
const runs = children(root, "w:r");
// ... 修改树结构 ...
const output = js2xml(root);
Copyright © 2026