Skip to content
Office Open

XML

Serialization

Convert Element trees back to XML strings with formatting options

#Basic Serialization

ts
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?)

ts
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
attributeValueFnfunction—Custom attribute value processor

#Formatted Output

ts
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:

ts
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);