XML

类型参考

XML 解析和序列化的核心 TypeScript 类型

Element

表示解析树中任意节点(元素、文本、注释、CDATA、处理指令)的核心类型。所有字段均为可选——元素通常使用 nameattributeselements

interface Element {
  declaration?: { attributes?: DeclarationAttributes };
  instruction?: string;
  attributes?: Attributes;
  cdata?: string;
  doctype?: string;
  comment?: string;
  text?: string | number | boolean;
  type?: string;
  name?: string;
  elements?: Element[];
  parent?: Element;
}

文本内容

文本不是独立的节点类型。<w:t>Hello</w:t> 的文本存储在元素自身的 text 字段上:

// 解析 <w:t>Hello</w:t>
{ type: "element", name: "w:t", text: "Hello" }

textOf(element) 读取(缺失时返回 "")。不存在 TextElement 接口。

创建 Element

将文本直接放在元素的 text 字段上——不要创建 { type: "text" } 子节点:

const paragraph: Element = {
  type: "element",
  name: "w:p",
  elements: [
    {
      type: "element",
      name: "w:r",
      elements: [{ type: "element", name: "w:t", text: "Hello World" }],
    },
  ],
};

Attributes

interface Attributes {
  [key: string]: string | number | undefined;
}

XML 属性的简单键值映射。

DeclarationAttributes

XML 声明(<?xml version="1.0" encoding="UTF-8"?>)的属性:

interface DeclarationAttributes {
  version?: string | number;
  encoding?: string;
  standalone?: string;
}

选项类型

接口中还保留若干 xml-js 风格的钩子字段(textFncdataFn 等),但下面只列出 parse() / stringify() 实际消费的字段。

ParseOptions

parse() 函数的选项:

interface ParseOptions {
  trim?: boolean;
  captureSpacesBetweenElements?: boolean;
  nativeTypeAttributes?: boolean;
  ignoreDeclaration?: boolean;
  ignoreComment?: boolean;
  ignoreCdata?: boolean;
  ignoreDoctype?: boolean;
  ignoreText?: boolean;
}

StringifyOptions

stringify() 函数的选项:

interface StringifyOptions {
  spaces?: number | string;
  fullTagEmptyElement?: boolean;
  indentText?: boolean;
  indentCdata?: boolean;
  ignoreDeclaration?: boolean;
  ignoreComment?: boolean;
  ignoreCdata?: boolean;
  ignoreDoctype?: boolean;
  ignoreText?: boolean;
  attributeValueFn?: (
    attributeValue: string,
    attributeName: string,
    currentElementName: string,
    currentElementObj: Element,
  ) => string;
}
Copyright © 2026