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 属性的简单键值映射。

XmlObject

底层 xml() 函数使用的 node-xml 兼容格式。标签名映射到内容描述符——_attr/_cdata 对象、原子值或它们的数组:

type XmlAtom = string | number | boolean | null;
type XmlObject = { [tag: string]: ElementObject | XmlDesc } | XmlDesc;

type XmlDesc =
  | { _attr: XmlAttrs }
  | { _cdata: string }
  | { _attr: XmlAttrs; _cdata: string }
  | XmlAtom
  | XmlAtom[];

示例:

const obj: XmlObject = {
  "w:p": [{ "w:r": [{ "w:t": ["Hello"] }] }],
};

XmlAttrs

node-xml 兼容对象的属性映射(值可为 null):

interface XmlAttrs {
  [attrName: string]: string | number | boolean | null;
}

选项类型

Xml2JsOptions

xml2js() 函数的选项:

interface Xml2JsOptions {
  trim?: boolean;
  sanitize?: boolean;
  nativeTypeAttributes?: boolean;
  ignoreDeclaration?: boolean;
  ignoreComment?: boolean;
  ignoreCdata?: boolean;
  ignoreDoctype?: boolean;
  ignoreText?: boolean;
  captureSpacesBetweenElements?: boolean;
  compact?: boolean;
}

Js2XmlOptions

js2xml() 函数的选项:

interface Js2XmlOptions {
  spaces?: number | string;
  fullTagEmptyElement?: boolean;
  ignoreDeclaration?: boolean;
  ignoreComment?: boolean;
  ignoreCdata?: boolean;
  ignoreDoctype?: boolean;
  ignoreText?: boolean;
  attributeValueFn?: (val: string, name: string) => string;
}
Copyright © 2026