CORE
Formatter
Convert XmlComponent trees to serializable XML objects and strings
The Formatter converts XmlComponent trees into plain objects or XML strings. It is used internally by the Packer to serialize documents.
Basic Usage
import { Formatter, XmlComponent } from "@office-open/core";
const formatter = new Formatter();
const component = new XmlComponent("w:p");
const context = { stack: [], file: {} };
const xmlObj = formatter.format(component, context);
// Returns IXmlableObject — a plain object representation
format()
Converts an XmlComponent tree to an IXmlableObject — a plain JavaScript object that can be further processed:
const xmlObj = formatter.format(component, context);
The returned object follows the xml-js Element structure with name, attributes, and elements fields.
formatToXml()
Converts an XmlComponent tree directly to an XML string:
const xml = formatter.formatToXml(component, context);
// '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<w:p/>'
const xmlNoDecl = formatter.formatToXml(component, context, false);
// '<w:p/>'
The third parameter controls whether to include the XML declaration.
Context
The IContext object is passed through the component tree during formatting:
interface IContext<TFileData = {}> {
stack: BaseXmlComponent[];
file: TFileData;
}
stack— Tracks the current component hierarchyfile— Carries file-level data (media, relationships, etc.)
When to Use
You typically don't use Formatter directly. The Packer handles serialization automatically. Use Formatter when you need to:
- Inspect the XML output of a component tree
- Build custom export pipelines
- Debug component structures