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
| Option | Type | Default | Description |
|---|---|---|---|
spaces | number | string | 0 | Indentation (number of spaces or string like "\t") |
fullTagEmptyElement | boolean | false | Use <tag></tag> instead of <tag/> for empty elements |
ignoreDeclaration | boolean | false | Omit XML declaration |
ignoreComment | boolean | false | Omit comments |
ignoreCdata | boolean | false | Omit CDATA sections |
ignoreDoctype | boolean | false | Omit DOCTYPE |
ignoreText | boolean | false | Omit text nodes |
attributeValueFn | function | — | Custom 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);