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 &lt;World&gt; &amp; &apos;Friends&apos;"

Escapes: &&amp;, <&lt;, >&gt;, "&quot;, '&apos;

escapeAttributeValue

Escape attribute values with additional handling for already-escaped entities:

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

escapeAttributeValue('value with "quotes"'); // 'value with &quot;quotes&quot;'

Unlike escapeXml, this function preserves already-escaped entities to prevent double-escaping.

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 undefined values
  • 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"/>'
Copyright © 2026