XML

Serialization

Convert Element trees back to XML strings with formatting options

Basic Serialization

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

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 = js2xml(root, { spaces: 2 });
// <w:p>
//   <w:r>
//     <w:t>Hello</w:t>
//   </w:r>
// </w:p>

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