XML
@office-open/xml
零依赖 XML 解析和序列化 — xml + xml-js 的直接替代品
安装
pnpm add @office-open/xml
npm install @office-open/xml
yarn add @office-open/xml
bun add @office-open/xml
API
xml2js(xml, options?)
将 XML 字符串解析为 Element 树。
import { xml2js } from "@office-open/xml";
const root = xml2js(`<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:r><w:t>Hello</w:t></w:r>
</w:p>`);
js2xml(root, options?)
将 Element 树序列化回 XML 字符串。
import { xml2js, js2xml } from "@office-open/xml";
const output = js2xml(root);
查询工具
| 函数 | 说明 |
|---|---|
findChild(parent, name) | 第一个匹配标签名的直接子元素 |
children(parent, name) | 所有匹配标签名的直接子元素 |
childText(parent, name) | 第一个匹配子元素的文本内容 |
attr(element, name) | 属性值(字符串) |
attrNum(element, name) | 属性值(数字) |
attrMeasure(element, name, type?) | 度量属性(保留单位) |
hasChild(parent, name) | 检查子元素是否存在 |
findDeep(parent, name) | 查找所有后代元素 |
findFirst(parent, name) | 首个后代(短路) |