CORE
XML 组件
构建 OOXML XML 元素树的基类和辅助工具
@office-open/docx 和 @office-open/pptx 中的所有 OOXML 元素都基于 XmlComponent 构建。本页介绍核心构建模块。
XmlComponent
OOXML 元素的主要基类。每个元素包装一个 XML 标签名并管理子元素。
import { XmlComponent } from "@office-open/core";
class MyElement extends XmlComponent {
constructor() {
super("w:myElement");
}
}
在构造时使用 root 添加子元素:
import { XmlComponent, onOffObj } from "@office-open/core";
class BoldElement extends XmlComponent {
constructor() {
super("w:b");
this.root.push(onOffObj("w:bCs", true));
}
}
元素构建器
零分配辅助函数,返回普通对象。优先使用这些函数而非已弃用的元素类。
| 函数 | 生成内容 | 示例 |
|---|---|---|
onOffObj(name, val?) | 布尔开关元素 | onOffObj("w:b", true) |
hpsMeasureObj(name, val) | 半磅测量值 | hpsMeasureObj("w:sz", 24) |
stringValObj(name, val) | 字符串值属性 | stringValObj("w:val", "hello") |
numberValObj(name, val) | 数值属性 | numberValObj("w:count", 3) |
stringEnumValObj(name, val) | 字符串枚举值 | stringEnumValObj("w:align", "center") |
stringContainerObj(name, val) | 包裹文本的元素 | stringContainerObj("w:t", "Hello") |
BuilderElement
具有显式属性和子元素配置的灵活元素:
import { BuilderElement } from "@office-open/core";
const el = new BuilderElement({
name: "w:spacing",
attributes: { before: 240, after: 120 },
children: [],
});
属性组件
XmlAttributeComponent
将 TypeScript 属性映射到 XML 属性名:
import { XmlAttributeComponent, XmlComponent } from "@office-open/core";
interface ISpacingAttributes {
readonly before?: number;
readonly after?: number;
}
class SpacingAttributes extends XmlAttributeComponent<ISpacingAttributes> {
protected readonly xmlKeys = { before: "w:before", after: "w:after" };
}
NextAttributeComponent
使用显式键值对,无需名称映射:
import { NextAttributeComponent } from "@office-open/core";
class MyAttributes extends NextAttributeComponent({
size: "w:sz",
color: "w:color",
}) {}
ImportedXmlComponent
将原始 XML 内容包装为可嵌入文档树的组件:
import { ImportedXmlComponent } from "@office-open/core";
const imported = ImportedXmlComponent.fromXmlString(
'<w:pPr xmlns:w="..."><w:jc w:val="center"/></w:pPr>',
);
convertToXmlComponent
将解析后的 Element(来自 @office-open/xml)转换为 XmlComponent 树:
import { convertToXmlComponent } from "@office-open/core";
import { parse } from "@office-open/xml";
const element = parse("<w:p><w:r><w:t>Hello</w:t></w:r></w:p>");
const component = convertToXmlComponent(element);
工具函数
wrapEl
将子组件包装在命名元素中:
import { wrapEl } from "@office-open/core";
const wrapped = wrapEl("w:rPr", someChildComponent);
其他组件
| 组件 | 说明 |
|---|---|
IgnoreIfEmptyXmlComponent | 为空时从 XML 输出中排除 |
InitializableXmlComponent | 可从另一个组件实例初始化 |
EmptyElement | 表示空的 XML 元素 |