XML
XML 转义
安全地转义和构建 XML 属性字符串
在编程构建 XML 内容时,特殊字符必须转义。escape 模块提供了安全的 XML 字符串处理工具。
escapeXml
转义 XML 元素内的文本内容:
import { escapeXml } from "@office-open/xml";
escapeXml("Hello <World> & 'Friends'"); // "Hello <World> & 'Friends'"
转义规则:& → &、< → <、> → >、" → "、' → '
escapeAttributeValue
转义属性值,额外处理已转义的实体:
import { escapeAttributeValue } from "@office-open/xml";
escapeAttributeValue('value with "quotes"'); // 'value with "quotes"'
与 escapeXml 不同,此函数保留已转义的实体,防止双重转义。
attrs
从记录对象构建 XML 属性字符串:
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=""'
- 自动跳过
undefined值 - 将数字转换为字符串
- 转义字符串值
构建元素
与其他函数结合构建 XML 片段:
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"/>'