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

js2xml

For xml-js compatibility, js2xml is available as an alias:

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

const xml = js2xml(element);

xml (node-xml format)

The xml function converts XmlObject (node-xml format) directly to XML:

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

const xmlString = xml(
    {
        "w:p": [{ "w:r": [{ "w:t": ["Hello"] }] }],
    },
    { indent: 2 },
);

This is more efficient than going through the Element intermediate format.

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