XML

Serialization

Convert Element trees back to XML strings with formatting options

Basic Serialization

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

Options

OptionTypeDefaultDescription
spacesnumber | string0Indentation (number of spaces or string like "\t")
fullTagEmptyElementbooleanfalseUse <tag></tag> instead of <tag/> for empty elements
indentTextbooleanfalseIndent text nodes by depth
indentCdatabooleanfalseIndent CDATA nodes by depth
ignoreDeclarationbooleanfalseOmit XML declaration
ignoreCommentbooleanfalseOmit comments
ignoreCdatabooleanfalseOmit CDATA sections
ignoreDoctypebooleanfalseOmit DOCTYPE
ignoreTextbooleanfalseOmit text nodes
attributeValueFnfunctionCustom attribute value processor

Formatted Output

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

Round-trip Example

Parse an XML string, modify the tree, and serialize back:

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");
// ... modify the tree ...
const output = stringify(root);
Copyright © 2026