跳到主要内容
Office Open

XML

XML 转义

安全地转义和构建 XML 属性字符串

在编程构建 XML 内容时,特殊字符必须转义。escape 模块提供了安全的 XML 字符串处理工具。

#escapeXml

转义 XML 元素内的文本内容:

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

escapeXml("Hello <World> & 'Friends'"); // "Hello &lt;World&gt; &amp; &apos;Friends&apos;"

转义规则:& → &amp;、< → &lt;、> → &gt;、" → &quot;、' → &apos;

#attrs

从记录对象构建 XML 属性字符串:

ts
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 片段:

ts
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"/>'