Skip to content

xml-model / index

index

Classes

XMLCodecError

Defined in: src/xml/codec.ts:9

Extends

  • Error

Constructors

Constructor

new XMLCodecError(rawMessage, path?, options?): XMLCodecError

Defined in: src/xml/codec.ts:13

Parameters
rawMessage

string

path?

readonly (string | number)[] = []

options?

ErrorOptions

Returns

XMLCodecError

Overrides

Error.constructor

Properties

cause?

optional cause?: unknown

Defined in: node_modules/typescript/lib/lib.es2022.error.d.ts:26

Inherited from

Error.cause

message

message: string

Defined in: node_modules/typescript/lib/lib.es5.d.ts:1077

Inherited from

Error.message

name

name: string

Defined in: node_modules/typescript/lib/lib.es5.d.ts:1076

Inherited from

Error.name

path

readonly path: readonly (string | number)[]

Defined in: src/xml/codec.ts:10

rawMessage

readonly rawMessage: string

Defined in: src/xml/codec.ts:11

stack?

optional stack?: string

Defined in: node_modules/typescript/lib/lib.es5.d.ts:1078

Inherited from

Error.stack

stackTraceLimit

static stackTraceLimit: number

Defined in: node_modules/@types/node/globals.d.ts:68

The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).

The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

Inherited from

Error.stackTraceLimit

Methods

captureStackTrace()

static captureStackTrace(targetObject, constructorOpt?): void

Defined in: node_modules/@types/node/globals.d.ts:52

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

js
function a() {
  b();
}

function b() {
  c();
}

function c() {
  // Create an error without stack trace to avoid calculating the stack trace twice.
  const { stackTraceLimit } = Error;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = stackTraceLimit;

  // Capture the stack trace above function b
  Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
  throw error;
}

a();
Parameters
targetObject

object

constructorOpt?

Function

Returns

void

Inherited from

Error.captureStackTrace

isError()

static isError(error): error is Error

Defined in: node_modules/typescript/lib/lib.esnext.error.d.ts:23

Indicates whether the argument provided is a built-in Error instance or not.

Parameters
error

unknown

Returns

error is Error

Inherited from

Error.isError

prepareStackTrace()

static prepareStackTrace(err, stackTraces): any

Defined in: node_modules/@types/node/globals.d.ts:56

Parameters
err

Error

stackTraces

CallSite[]

Returns

any

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from

Error.prepareStackTrace

Interfaces

XMLState

Defined in: src/xml/codec.ts:261

Properties

sequence

sequence: OrderEntry[]

Defined in: src/xml/codec.ts:263

Preserves element ordering and unknown elements across a decode → encode round-trip.

source?

optional source?: object

Defined in: src/xml/codec.ts:265

Present when xmlStateSchema({ source: true }) is used: the original XMLElement.

attributes?

optional attributes?: Record<string, string>

elements?

optional elements?: ({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]

name

name: string

type

type: "element"

Type Aliases

ModelConstructor()

ModelConstructor<S, Inst> = Inst

Defined in: src/model.ts:20

Constructor type for model classes.

S — the ZodObject schema (drives field types) Inst — the actual instance type produced by new. Defaults to z.infer<S>. extend() widens it to InstanceType<Self> & z.infer<ExtendedSchema> so that parent class methods survive into child instances.

Type Parameters

S

S extends z.ZodObject<any> = z.ZodObject<any>

Inst

Inst extends z.infer<S> = z.infer<S>

new ModelConstructor(data): Inst

Constructor type for model classes.

S — the ZodObject schema (drives field types) Inst — the actual instance type produced by new. Defaults to z.infer<S>. extend() widens it to InstanceType<Self> & z.infer<ExtendedSchema> so that parent class methods survive into child instances.

Parameters

data

output<S>

Returns

Inst

Properties

dataSchema

readonly dataSchema: S

Defined in: src/model.ts:25

Methods

extend()

extend<Self, U>(this, extension, meta?): Omit<Self, keyof ModelConstructor<S, Inst>> & ModelConstructor<ZodObject<{ [k in string | number | symbol]: ((keyof S["shape"] & keyof U) extends never ? S["shape"] & U : { [K in string | number | symbol as K extends keyof (...) ? never : K]: (...)[(...)][K] } & { [K in string | number | symbol]: U[K] })[k] }, $strip>, InstanceType<Self> & $InferObjectOutput<{ [k in string | number | symbol]: ((keyof (...)[(...)] & keyof U) extends never ? S["shape"] & U : { [K in (...) | (...) | (...) as (...) extends (...) ? (...) : (...)]: (...)[(...)] } & { [K in (...) | (...) | (...)]: (...)[(...)] })[k] }, { }>>

Defined in: src/model.ts:59

Creates a new model class that truly extends this one — inheriting its prototype chain and methods — while adding new schema fields.

Pass an optional meta object (e.g. xml.root({ tagname: "car" })) to attach Zod schema metadata to the extended schema. Multiple codec metas compose with spread: { ...xml.root({ tagname: "car" }), ...otherCodec.meta({...}) }

Type Parameters
Self

Self extends ModelConstructor<S, Inst>

U

U extends $ZodLooseShape

Parameters
this

Self

extension

U

meta?

GlobalMeta

Returns

Omit<Self, keyof ModelConstructor<S, Inst>> & ModelConstructor<ZodObject<{ [k in string | number | symbol]: ((keyof S["shape"] & keyof U) extends never ? S["shape"] & U : { [K in string | number | symbol as K extends keyof (...) ? never : K]: (...)[(...)][K] } & { [K in string | number | symbol]: U[K] })[k] }, $strip>, InstanceType<Self> & $InferObjectOutput<{ [k in string | number | symbol]: ((keyof (...)[(...)] & keyof U) extends never ? S["shape"] & U : { [K in (...) | (...) | (...) as (...) extends (...) ? (...) : (...)]: (...)[(...)] } & { [K in (...) | (...) | (...)]: (...)[(...)] })[k] }, { }>>

fromData()

fromData<T>(this, data): InstanceType<T>

Defined in: src/model.ts:39

Override to customise instantiation — e.g. to inject extra constructor arguments. Called by from() instead of new this(data) directly.

Type Parameters
T

T extends (...args) => any

Parameters
this

T

data

output<S>

Returns

InstanceType<T>

schema()

schema<T>(this): ZodCodec<S, ZodCustom<InstanceType<T>, InstanceType<T>>>

Defined in: src/model.ts:31

Returns a ZodCodec that transforms parsed data into a class instance (and can go the other way around). Use inside xml.prop() or z.array(...).

Type Parameters
T

T extends (...args) => any

Parameters
this

T

Returns

ZodCodec<S, ZodCustom<InstanceType<T>, InstanceType<T>>>

toData()

toData<T>(this, instance): output<S>

Defined in: src/model.ts:46

Returns the raw decoded data object stored on the instance — the same object that was passed to the constructor, including any non-enumerable symbol metadata (e.g. XML_STATE) that survived construction.

Type Parameters
T

T extends (...args) => any

Parameters
this

T

instance

InstanceType<T>

Returns

output<S>


ParseOptions

ParseOptions = IgnoreOptions & ChangingKeyNames & object

Defined in: src/xml/xml-js.ts:89

Options for parsing XML into a JS object tree.

Type Declaration

addParent?

optional addParent?: boolean

Whether to add a parent property on each element pointing back to its parent. Useful for upward traversal but creates circular references.

Default
ts
false
attributeNameFn?

optional attributeNameFn?: (attributeName, attributeValue, parentElement) => void

Custom processing hook called for each attribute name.

Parameters
attributeName

string

attributeValue

string

parentElement

string

Returns

void

attributesFn?

optional attributesFn?: (value, parentElement) => void

Custom processing hook called for the whole attributes object of an element.

Parameters
value

string

parentElement

string

Returns

void

attributeValueFn?

optional attributeValueFn?: (attributeValue, attributeName, parentElement) => void

Custom processing hook called for each attribute value.

Parameters
attributeValue

string

attributeName

string

parentElement

string

Returns

void

captureSpacesBetweenElements?

optional captureSpacesBetweenElements?: boolean

Whether to preserve whitespace-only text nodes that appear between elements.

Default
ts
false
cdataFn?

optional cdataFn?: (value, parentElement) => void

Custom processing hook called for each CData section.

Parameters
value

string

parentElement

object

Returns

void

commentFn?

optional commentFn?: (value, parentElement) => void

Custom processing hook called for each comment.

Parameters
value

string

parentElement

object

Returns

void

doctypeFn?

optional doctypeFn?: (value, parentElement) => void

Custom processing hook called for each DOCTYPE value.

Parameters
value

string

parentElement

object

Returns

void

elementNameFn?

optional elementNameFn?: (value, parentElement) => void

Custom processing hook called for each element name.

Parameters
value

string

parentElement

object

Returns

void

instructionFn?

optional instructionFn?: (instructionValue, instructionName, parentElement) => void

Custom processing hook called for each processing instruction value.

Parameters
instructionValue

string

instructionName

string

parentElement

string

Returns

void

instructionHasAttributes?

optional instructionHasAttributes?: boolean

Whether to parse the contents of processing instructions as attributes. <?go to="there"?> becomes { go: { attributes: { to: "there" } } } instead of { go: 'to="there"' }.

Default
ts
false
instructionNameFn?

optional instructionNameFn?: (instructionName, instructionValue, parentElement) => void

Custom processing hook called for each processing instruction name.

Parameters
instructionName

string

instructionValue

string

parentElement

string

Returns

void

nativeType?

optional nativeType?: boolean

Whether to coerce numeric and boolean text values to their native JS types.

Default
ts
false
sanitize?

optional sanitize?: boolean

Whether to replace &, <, > with their XML entities in text nodes.

Deprecated

See https://github.com/nashwaan/xml-js/issues/26

Default
ts
false
textFn?

optional textFn?: (value, parentElement) => void

Custom processing hook called for each text node.

Parameters
value

string

parentElement

object

Returns

void

trim?

optional trim?: boolean

Whether to trim whitespace surrounding text content.

Default
ts
false

StringifyOptions

StringifyOptions = IgnoreOptions & ChangingKeyNames & object

Defined in: src/xml/xml-js.ts:165

Options for serializing a JS object tree back to XML.

Type Declaration

attributeNameFn?

optional attributeNameFn?: (attributeName, attributeValue, currentElementName, currentElementObj) => void

Custom processing hook called for each attribute name.

Parameters
attributeName

string

attributeValue

string

currentElementName

string

currentElementObj

object

Returns

void

attributesFn?

optional attributesFn?: (value, currentElementName, currentElementObj) => void

Custom processing hook called for the whole attributes object of an element.

Parameters
value

string

currentElementName

string

currentElementObj

object

Returns

void

attributeValueFn?

optional attributeValueFn?: (attributeValue, attributeName, currentElementName, currentElementObj) => void

Custom processing hook called for each attribute value.

Parameters
attributeValue

string

attributeName

string

currentElementName

string

currentElementObj

object

Returns

void

cdataFn?

optional cdataFn?: (value, currentElementName, currentElementObj) => void

Custom processing hook called for each CData section.

Parameters
value

string

currentElementName

string

currentElementObj

object

Returns

void

commentFn?

optional commentFn?: (value, currentElementName, currentElementObj) => void

Custom processing hook called for each comment.

Parameters
value

string

currentElementName

string

currentElementObj

object

Returns

void

doctypeFn?

optional doctypeFn?: (value, currentElementName, currentElementObj) => void

Custom processing hook called for each DOCTYPE value.

Parameters
value

string

currentElementName

string

currentElementObj

object

Returns

void

elementNameFn?

optional elementNameFn?: (value, currentElementName, currentElementObj) => void

Custom processing hook called for each element name.

Parameters
value

string

currentElementName

string

currentElementObj

object

Returns

void

fullTagEmptyElement?

optional fullTagEmptyElement?: boolean

Whether to emit empty elements as full tag pairs (<a></a>) instead of self-closing (<a/>).

Default
ts
false
fullTagEmptyElementFn?

optional fullTagEmptyElementFn?: (currentElementName, currentElementObj) => void

Per-element override for fullTagEmptyElement. Return true to emit a full tag pair for the given element, false for self-closing.

Parameters
currentElementName

string

currentElementObj

object

Returns

void

indentAttributes?

optional indentAttributes?: boolean

Whether to print each attribute on its own indented line (when spaces is set).

Default
ts
false
indentCdata?

optional indentCdata?: boolean

Whether to write CData sections on a new indented line.

Default
ts
false
indentInstruction?

optional indentInstruction?: boolean

Whether to indent processing instructions onto their own line.

Default
ts
false
indentText?

optional indentText?: boolean

Whether to indent text nodes onto their own line when spaces is set.

Default
ts
false
instructionFn?

optional instructionFn?: (instructionValue, instructionName, currentElementName, currentElementObj) => void

Custom processing hook called for each processing instruction value.

Parameters
instructionValue

string

instructionName

string

currentElementName

string

currentElementObj

object

Returns

void

instructionNameFn?

optional instructionNameFn?: (instructionName, instructionValue, currentElementName, currentElementObj) => void

Custom processing hook called for each processing instruction name.

Parameters
instructionName

string

instructionValue

string

currentElementName

string

currentElementObj

object

Returns

void

noQuotesForNativeAttributes?

optional noQuotesForNativeAttributes?: boolean

Whether to omit quotes around attribute values that are native JS types (numbers, booleans).

Default
ts
false
spaces?

optional spaces?: number | string

Number of spaces (or a string like '\t') to use for indenting XML output.

Default
ts
0
textFn?

optional textFn?: (value, currentElementName, currentElementObj) => void

Custom processing hook called for each text node.

Parameters
value

string

currentElementName

string

currentElementObj

object

Returns

void


UserCodecOptions

UserCodecOptions<S> = object

Defined in: src/xml/codec.ts:71

Stored in schema meta under the single @@xml-model key. All fields are optional; normalizeCodecOptions fills in defaults. tagname/propertyTagname accept a string (normalized to a function). propertyMatch accepts a RegExp (normalized to an element-name test).

Type Parameters

S

S extends z.ZodType = z.ZodType

Properties

decode?

optional decode?: (ctx, next) => z.input<S>

Defined in: src/xml/codec.ts:73

Parameters
ctx

RootDecodingContext<S>

next

() => z.input<S>

Returns

z.input<S>

decodeAsProperty?

optional decodeAsProperty?: CodecOptions<S>["decodeAsProperty"]

Defined in: src/xml/codec.ts:78

encode?

optional encode?: (ctx, next) => XMLElement

Defined in: src/xml/codec.ts:74

Parameters
ctx

RootEncodingContext<S>

next

() => XMLElement

Returns

XMLElement

encodeAsProperty?

optional encodeAsProperty?: CodecOptions<S>["encodeAsProperty"]

Defined in: src/xml/codec.ts:79

inlineProperty?

optional inlineProperty?: boolean

Defined in: src/xml/codec.ts:76

propertyMatch?

optional propertyMatch?: RegExp | CodecOptions<S>["propertyMatch"]

Defined in: src/xml/codec.ts:77

propertyTagname?

optional propertyTagname?: string | CodecOptions<S>["propertyTagname"]

Defined in: src/xml/codec.ts:75

tagname?

optional tagname?: string | CodecOptions<S>["tagname"]

Defined in: src/xml/codec.ts:72


XMLCommentNode

XMLCommentNode = z.infer<typeof ZXMLCommentNode>

Defined in: src/xml/xml-js.ts:17


XMLElement

XMLElement = XMLElementNode

Defined in: src/xml/xml-js.ts:34

A single node in the xml-js element tree. Used as the internal representation for all XML parsing and serialization.


XMLElementNode

XMLElementNode = z.infer<typeof ZXMLElementNode>

Defined in: src/xml/xml-js.ts:14


XmlModelConstructor

XmlModelConstructor<S, Inst> = ModelConstructor<S, Inst> & object

Defined in: src/xml/model.ts:14

Constructor type for xmlModel classes. Extends ModelConstructor with XML-specific helpers and a typed extend().

Type Declaration

fromXML()

fromXML<T>(this, xmlInput): InstanceType<T>

Returns a new instance parsed from an XML string or XMLRoot.

Type Parameters
T

T extends (...args) => any

Parameters
this

T

xmlInput

string | { attributes?: Record<string, string>; elements?: ({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]; name: string; type: "element"; } | XMLRoot

Returns

InstanceType<T>

toXML()

toXML(instance): XMLRoot

Converts an instance to an XMLRoot document tree.

Parameters
instance

output<S>

Returns

XMLRoot

toXMLString()

toXMLString(instance, options?): string

Converts an instance to an XML string.

Parameters
instance

output<S>

options?

StringifyOptions

Returns

string

Type Parameters

S

S extends z.ZodObject<any> = z.ZodObject<any>

Inst

Inst extends z.infer<S> = z.infer<S>


XMLNode

XMLNode = XMLElementNode | XMLCommentNode | XMLTextNode

Defined in: src/xml/xml-js.ts:23


XMLRoot

XMLRoot = object

Defined in: src/xml/xml-js.ts:41

The root of an xml-js document: a wrapper object whose elements array holds top-level nodes.

the elements array contains AT MOST one node with type element

Properties

elements

elements: XMLNode[]

Defined in: src/xml/xml-js.ts:41


XMLTextNode

XMLTextNode = z.infer<typeof ZXMLTextNode>

Defined in: src/xml/xml-js.ts:20


XMLVoid

XMLVoid = EmptyObj

Defined in: src/xml/xml-js.ts:44

Variables

DATA

const DATA: typeof DATA

Defined in: src/model.ts:10

Stores the raw data object on model instances.


xml

const xml: object

Defined in: src/xml/schema-meta.ts:206

Namespace object for XML metadata helpers.

Type Declaration

attr

attr: {<PS>(schema, options?): PS; (options?): GlobalMeta; }

Call Signature

<PS>(schema, options?): PS

Type Parameters
PS

PS extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Parameters
schema

PS

options?

AttributePropOptions

Returns

PS

Call Signature

(options?): GlobalMeta

Parameters
options?

AttributePropOptions

Returns

GlobalMeta

prop

prop: {<PS>(schema, options): PS; (options): GlobalMeta; }

Call Signature

<PS>(schema, options): PS

Annotate a field schema with XML child-element options.

xml.prop() with no options is a no-op. The codec already iterates all ZodObject fields and defaults the tag name to kebabCase(fieldKey). Wrap a schema in xml.prop() only when you need to customise at least one of: tagname, inline, match, decode, or encode.

Type Parameters
PS

PS extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Parameters
schema

PS

options

UserPropOptions

Returns

PS

Example
ts
// ✅ Needed — custom tagname
xml.prop(z.string(), { tagname: "pub-date" })

// ✅ Needed — inline (children promoted to parent)
xml.prop(z.array(ItemSchema), { inline: true })

// ⚠️  Redundant — equivalent to plain z.string()
xml.prop(z.string())
Call Signature

(options): GlobalMeta

Annotate a field schema with XML child-element options.

xml.prop() with no options is a no-op. The codec already iterates all ZodObject fields and defaults the tag name to kebabCase(fieldKey). Wrap a schema in xml.prop() only when you need to customise at least one of: tagname, inline, match, decode, or encode.

Parameters
options

UserPropOptions

Returns

GlobalMeta

Example
ts
// ✅ Needed — custom tagname
xml.prop(z.string(), { tagname: "pub-date" })

// ✅ Needed — inline (children promoted to parent)
xml.prop(z.array(ItemSchema), { inline: true })

// ⚠️  Redundant — equivalent to plain z.string()
xml.prop(z.string())
root

root: {<S>(schema, options): S; (options): GlobalMeta; }

Call Signature

<S>(schema, options): S

Type Parameters
S

S extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Parameters
schema

S

options

UserRootOptions<S>

Returns

S

Call Signature

(options): GlobalMeta

Parameters
options

UserRootOptions

Returns

GlobalMeta


XML

const XML: object

Defined in: src/xml/xml-js.ts:342

Namespace object bundling all XML utility functions.

Type Declaration

addElement

addElement: (xml, element) => void

Appends a child element to xml, initialising the elements array if needed.

Parameters
xml

The parent element to modify.

attributes?

Record<string, string> = ...

elements?

({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]

name

string = ...

type

"element" = ...

element

The child element to append.

attributes?

Record<string, string> = ...

elements?

({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]

name

string = ...

type

"element" = ...

Returns

void

deleteAttribute

deleteAttribute: (xml, attribute) => void

Removes an attribute from an element. Does nothing if the element has no attributes.

Parameters
xml

The element to modify.

attributes?

Record<string, string> = ...

elements?

({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]

name

string = ...

type

"element" = ...

attribute

string

The attribute name to remove.

Returns

void

elementFromRoot

elementFromRoot: (root) => object

Parameters
root

XMLRoot

Returns

object

attributes?

optional attributes?: Record<string, string>

elements?

optional elements?: ({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]

name

name: string

type

type: "element"

fromContent

fromContent: {(content): object; (content, tag, attributes?): object; }

Call Signature

(content): object

Creates a text-only fragment wrapping the given content.

Parameters
content

string

The text content to wrap (defaults to empty string).

Returns

object

elements

elements: [{ text: string; type: "text"; }] | []

Call Signature

(content, tag, attributes?): object

Creates a full element wrapping the given text content.

Parameters
content

string

The text content to wrap (defaults to empty string).

tag

string

Element tag name.

attributes?

Record<string, string>

Optional attributes.

Returns

object

attributes?

optional attributes?: Record<string, string>

elements

elements: [] | [{ text: string; type: "text"; }]

name

name: string

type

type: "element"

getContent

getContent: (xml) => string

Extracts the text content from an element that has a single text child node.

Parameters
xml

An XMLElement expected to contain a single text node.

attributes?

Record<string, string> = ...

elements?

({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]

name

string = ...

type

"element" = ...

Returns

string

The text value, or an empty string when there are no child elements.

Throws

When the element has multiple or non-text children.

isEmpty

isEmpty: (xml) => xml is EmptyObj

Parameters
xml

object

Returns

xml is EmptyObj

isRoot

isRoot: (xml) => xml is XMLRoot

Parameters
xml

object

Returns

xml is XMLRoot

parse

parse: (xml, options) => XMLRoot

Parameters
xml

string

options?

ParseOptions = {}

Returns

XMLRoot

setAttribute

setAttribute: (xml, attribute, value) => void

Sets an attribute on an element, initialising the attributes map if needed.

Parameters
xml

The element to modify.

attributes?

Record<string, string> = ...

elements?

({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]

name

string = ...

type

"element" = ...

attribute

string

The attribute name.

value

string

The attribute value.

Returns

void

stringify

stringify: (xml, options) => string

Parameters
xml

XMLRoot

options?

StringifyOptions = {}

Returns

string


ZXMLCommentNode

const ZXMLCommentNode: ZodObject<{ comment: ZodString; type: ZodLiteral<"comment">; }, $strip>

Defined in: src/xml/xml-js.ts:16


ZXMLElementNode

const ZXMLElementNode: ZodObject<{ attributes: ZodOptional<ZodRecord<ZodString, ZodString>>; elements: ZodOptional<ZodArray<ZodDiscriminatedUnion<[ZodObject<{ type: ZodLiteral<"element">; name: ZodString; attributes: ZodOptional<ZodRecord<ZodString, ZodString>>; elements: ZodOptional<...>; }, $strip>, ZodObject<{ comment: ZodString; type: ZodLiteral<"comment">; }, $strip>, ZodObject<{ text: ZodString; type: ZodLiteral<"text">; }, $strip>], "type">>>; name: ZodString; type: ZodLiteral<"element">; }, $strip>

Defined in: src/xml/xml-js.ts:4


ZXMLNode

const ZXMLNode: z.ZodDiscriminatedUnion<[typeof ZXMLElementNode, typeof ZXMLCommentNode, typeof ZXMLTextNode], "type">

Defined in: src/xml/xml-js.ts:25


ZXMLRoot

const ZXMLRoot: ZodObject<{ elements: ZodArray<ZodDiscriminatedUnion<[ZodObject<{ attributes: ZodOptional<ZodRecord<ZodString, ZodString>>; elements: ZodOptional<ZodArray<ZodDiscriminatedUnion<[ZodObject<{ type: ZodLiteral<"element">; name: ZodString; attributes: ZodOptional<ZodRecord<ZodString, ZodString>>; elements: ZodOptional<...>; }, $strip>, ZodObject<...>, ZodObject<...>], "type">>>; name: ZodString; type: ZodLiteral<"element">; }, $strip>, ZodObject<{ comment: ZodString; type: ZodLiteral<"comment">; }, $strip>, ZodObject<{ text: ZodString; type: ZodLiteral<"text">; }, $strip>], "type">>; }, $strip>

Defined in: src/xml/xml-js.ts:36


ZXMLTextNode

const ZXMLTextNode: ZodObject<{ text: ZodString; type: ZodLiteral<"text">; }, $strip>

Defined in: src/xml/xml-js.ts:19

Functions

isModel()

isModel(cls): cls is ModelConstructor<ZodObject<any, $strip>, Record<string, unknown>>

Defined in: src/model.ts:71

Returns true if cls is a class produced by model() (or a subclass of one).

Parameters

cls

unknown

Returns

cls is ModelConstructor<ZodObject<any, $strip>, Record<string, unknown>>


model()

model<S>(schema): ModelConstructor<S>

Defined in: src/model.ts:99

Generic class factory. Creates a class with typed instance properties and codec-agnostic from()/to() methods.

Codec-specific factories (e.g. xmlModel) wrap this and inject named helpers.

Type Parameters

S

S extends ZodObject<any, $strip>

Parameters

schema

S

Returns

ModelConstructor<S>

Example

ts
class Book extends model(z.object({ title: z.string() })) {}

normalizeCodecOptions()

normalizeCodecOptions<S>(schema, options?, parent?): CodecOptions<S>

Defined in: src/xml/codec.ts:118

Type Parameters

S

S extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Parameters

schema

S

options?

UserCodecOptions<S> = {}

parent?

CodecOptions<ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>> = undefined

Returns

CodecOptions<S>


parseXML()

parseXML<S>(schema, input): output<S>

Defined in: src/xml/codec.ts:389

Parses an XML string, XMLRoot, or XMLElement into the output type of schema (z.output<S>), running the full pipeline: XML → decodeschema.parse().

z.codec transforms (e.g. string → Date) and default values are applied. Use the lower-level decode if you need the raw input-type value without running the Zod parse pipeline.

Type Parameters

S

S extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Parameters

schema

S

input

string | { attributes?: Record<string, string>; elements?: ({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]; name: string; type: "element"; } | XMLRoot

Returns

output<S>


registerDefault()

registerDefault(resolve): void

Defined in: src/xml/codec.ts:435

Parameters

resolve

DefaultResolver

Returns

void


stringifyXML()

stringifyXML<S>(schema, data, options?): string

Defined in: src/xml/codec.ts:422

Converts a value at the output type of schema (z.output<S>) into an XML string, running the full pipeline: schema.encode()encodeXML.stringify.

Equivalent to XML.stringify({ elements: [toXML(schema, data)] }, options).

Type Parameters

S

S extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Parameters

schema

S

data

output<S>

options?

StringifyOptions

Returns

string


toXML()

toXML<S>(schema, data): object

Defined in: src/xml/codec.ts:412

Converts a value at the output type of schema (z.output<S>) into an XMLElement, running the full pipeline: schema.encode()encode.

z.codec transforms are reversed before the XML adapter runs. Use the lower-level encode if you already have an input-type value and do not need to run the Zod encode pipeline.

Does not accept nullable values — check for null/undefined before calling.

Type Parameters

S

S extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Parameters

schema

S

data

output<S>

Returns

object

attributes?

optional attributes?: Record<string, string>

elements?

optional elements?: ({ attributes?: Record<string, string>; elements?: ({ type: "element"; name: string; attributes?: Record<string, string>; elements?: (... | { type: "comment"; comment: string; } | { type: "text"; text: string; })[]; } | { type: "comment"; comment: string; } | { ...; })[]; name: string; type: "element"; } | { comment: string; type: "comment"; } | { text: string; type: "text"; })[]

name

name: string

type

type: "element"


xmlCodec()

xmlCodec<S>(schema): ZodCodec<ZodString, S>

Defined in: src/xml/codec.ts:965

Creates a z.codec that converts between an XML string and the input type of schema (z.input<S>).

The codec sits at the XML ↔ z.input<S> boundary only — it does not run Zod's parse pipeline. z.codec transforms (e.g. string → Date) and class instantiation are left to schema.parse() / schema.encode(), which you call separately if needed.

Typical use: xmlCodec(MyClass.dataSchema) for standalone encode/decode without going through the full fromXML / toXMLString class API.

Type Parameters

S

S extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Parameters

schema

S

Returns

ZodCodec<ZodString, S>


xmlModel()

xmlModel<S>(schema, options?): XmlModelConstructor<S>

Defined in: src/xml/model.ts:31

Type Parameters

S

S extends ZodObject<any, $strip>

Parameters

schema

S

options?

UserCodecOptions<S>

Returns

XmlModelConstructor<S>


xmlStateSchema()

Call Signature

xmlStateSchema(): ZodOptional<ZodCustom<XMLState, unknown>>

Defined in: src/xml/codec.ts:293

Schema for the XML round-trip state field.

Add a field with this schema to any xmlModel ZodObject to opt in to:

  • Element ordering — elements are re-emitted in source order, not schema order.
  • Unknown elements — unrecognised elements are passed through verbatim on re-encode.

The field can be named anything; the codec detects it automatically. Pass { source: true } to additionally store the original XMLElement on the instance.

Returns

ZodOptional<ZodCustom<XMLState, unknown>>

Example
ts
class Device extends xmlModel(z.object({
  _xmlState: xmlStateSchema(),
  name: z.string(),
}), { tagname: "device" }) {}

// With source recording:
class Device extends xmlModel(z.object({
  _xmlState: xmlStateSchema({ source: true }),
  name: z.string(),
}), { tagname: "device" }) {}

Call Signature

xmlStateSchema(options): ZodOptional<ZodCustom<XMLState & object, unknown>>

Defined in: src/xml/codec.ts:294

Schema for the XML round-trip state field.

Add a field with this schema to any xmlModel ZodObject to opt in to:

  • Element ordering — elements are re-emitted in source order, not schema order.
  • Unknown elements — unrecognised elements are passed through verbatim on re-encode.

The field can be named anything; the codec detects it automatically. Pass { source: true } to additionally store the original XMLElement on the instance.

Parameters
options
source

true

Returns

ZodOptional<ZodCustom<XMLState & object, unknown>>

Example
ts
class Device extends xmlModel(z.object({
  _xmlState: xmlStateSchema(),
  name: z.string(),
}), { tagname: "device" }) {}

// With source recording:
class Device extends xmlModel(z.object({
  _xmlState: xmlStateSchema({ source: true }),
  name: z.string(),
}), { tagname: "device" }) {}