XML

类型参考

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

Element

表示解析树中 XML 元素的核心类型:

interface Element {
    type: "element";
    name: string;
    attributes?: Record<string, string>;
    elements?: Element[];
}

文本节点使用不同的结构:

interface TextElement {
    type: "text";
    text: string;
}

创建 Element

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

Attributes

interface Attributes {
    [key: string]: string;
}

XML 属性的简单键值映射。

XmlObject

xml() 函数使用的 node-xml 兼容格式:

interface XmlObject {
    [elementName: string]: (XmlObject | string)[];
}

示例:

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

XmlAttrs

node-xml 兼容对象的属性格式:

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

选项类型

Xml2JsOptions

parse() 函数的选项:

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

Js2XmlOptions

stringify() 函数的选项:

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