Skip to content
Office Open

XML

Type Reference

Core TypeScript types for XML parsing and serialization

#Element

The core type representing any node in the parsed tree (elements, text, comments, CDATA, processing instructions). All fields are optional — an element typically uses name, attributes, and elements:

ts
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;
}

#Text content

Text is not a separate node type. The text of <w:t>Hello</w:t> is stored on the element's own text field:

ts
// parsed <w:t>Hello</w:t>
{ type: "element", name: "w:t", text: "Hello" }

Read it with textOf(element) (returns "" when absent). There is no TextElement interface.

#Creating Elements

Put text directly on the element's text field — do not create { type: "text" } children:

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

#Attributes

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

A simple key-value map for XML attributes.

#DeclarationAttributes

Attributes of the XML declaration (<?xml version="1.0" encoding="UTF-8"?>):

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

#Option Types

The interfaces also retain several xml-js-style hook fields (textFn, cdataFn, etc.), but only the fields actually consumed by parse()/stringify() are listed below.

#ParseOptions

Options for the parse() function:

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

#StringifyOptions

Options for the stringify() function:

ts
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;
}