XML
XML Escape
Escape and build XML attribute strings safely
When constructing XML content programmatically, special characters must be escaped. The escape module provides utilities for safe XML string handling.
#escapeXml
Escape text content for use inside XML elements:
import { escapeXml } from "@office-open/xml";
escapeXml("Hello <World> & 'Friends'"); // "Hello <World> & 'Friends'"
Escapes: & → &, < → <, > → >, " → ", ' → '
#attrs
Build an XML attribute string from a record:
import { attrs } from "@office-open/xml";
const attrStr = attrs({
"w:val": "single",
"w:sz": 4,
"w:space": "",
"w:color": undefined,
});
// ' w:val="single" w:sz="4" w:space=""'
- Automatically skips
undefinedvalues - Converts numbers to strings
- Escapes string values
#Building Elements
Combine with other functions to build XML fragments:
import { attrs, escapeXml } from "@office-open/xml";
const name = "w:spacing";
const attributes = attrs({ "w:before": "240", "w:after": "120" });
const xml = `<${name}${attributes}/>`;
// '<w:spacing w:before="240" w:after="120"/>'