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
Overrides
Error.constructor
Properties
cause?
optionalcause?: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
readonlypath: readonly (string|number)[]
Defined in: src/xml/codec.ts:10
rawMessage
readonlyrawMessage:string
Defined in: src/xml/codec.ts:11
stack?
optionalstack?:string
Defined in: node_modules/typescript/lib/lib.es5.d.ts:1078
Inherited from
Error.stack
stackTraceLimit
staticstackTraceLimit: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()
staticcaptureStackTrace(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.
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:
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()
staticisError(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()
staticprepareStackTrace(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?
optionalsource?:object
Defined in: src/xml/codec.ts:265
Present when xmlStateSchema({ source: true }) is used: the original XMLElement.
attributes?
optionalattributes?:Record<string,string>
elements?
optionalelements?: ({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
readonlydataSchema:S
Defined in: src/model.ts:25
Methods
extend()
extend<
Self,U>(this,extension,meta?):Omit<Self, keyofModelConstructor<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?
optionaladdParent?:boolean
Whether to add a parent property on each element pointing back to its parent. Useful for upward traversal but creates circular references.
Default
falseattributeNameFn?
optionalattributeNameFn?: (attributeName,attributeValue,parentElement) =>void
Custom processing hook called for each attribute name.
Parameters
attributeName
string
attributeValue
string
parentElement
string
Returns
void
attributesFn?
optionalattributesFn?: (value,parentElement) =>void
Custom processing hook called for the whole attributes object of an element.
Parameters
value
string
parentElement
string
Returns
void
attributeValueFn?
optionalattributeValueFn?: (attributeValue,attributeName,parentElement) =>void
Custom processing hook called for each attribute value.
Parameters
attributeValue
string
attributeName
string
parentElement
string
Returns
void
captureSpacesBetweenElements?
optionalcaptureSpacesBetweenElements?:boolean
Whether to preserve whitespace-only text nodes that appear between elements.
Default
falsecdataFn?
optionalcdataFn?: (value,parentElement) =>void
Custom processing hook called for each CData section.
Parameters
value
string
parentElement
object
Returns
void
commentFn?
optionalcommentFn?: (value,parentElement) =>void
Custom processing hook called for each comment.
Parameters
value
string
parentElement
object
Returns
void
doctypeFn?
optionaldoctypeFn?: (value,parentElement) =>void
Custom processing hook called for each DOCTYPE value.
Parameters
value
string
parentElement
object
Returns
void
elementNameFn?
optionalelementNameFn?: (value,parentElement) =>void
Custom processing hook called for each element name.
Parameters
value
string
parentElement
object
Returns
void
instructionFn?
optionalinstructionFn?: (instructionValue,instructionName,parentElement) =>void
Custom processing hook called for each processing instruction value.
Parameters
instructionValue
string
instructionName
string
parentElement
string
Returns
void
instructionHasAttributes?
optionalinstructionHasAttributes?: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
falseinstructionNameFn?
optionalinstructionNameFn?: (instructionName,instructionValue,parentElement) =>void
Custom processing hook called for each processing instruction name.
Parameters
instructionName
string
instructionValue
string
parentElement
string
Returns
void
nativeType?
optionalnativeType?:boolean
Whether to coerce numeric and boolean text values to their native JS types.
Default
falsesanitize?
optionalsanitize?:boolean
Whether to replace &, <, > with their XML entities in text nodes.
Deprecated
See https://github.com/nashwaan/xml-js/issues/26
Default
falsetextFn?
optionaltextFn?: (value,parentElement) =>void
Custom processing hook called for each text node.
Parameters
value
string
parentElement
object
Returns
void
trim?
optionaltrim?:boolean
Whether to trim whitespace surrounding text content.
Default
falseStringifyOptions
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?
optionalattributeNameFn?: (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?
optionalattributesFn?: (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?
optionalattributeValueFn?: (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?
optionalcdataFn?: (value,currentElementName,currentElementObj) =>void
Custom processing hook called for each CData section.
Parameters
value
string
currentElementName
string
currentElementObj
object
Returns
void
commentFn?
optionalcommentFn?: (value,currentElementName,currentElementObj) =>void
Custom processing hook called for each comment.
Parameters
value
string
currentElementName
string
currentElementObj
object
Returns
void
doctypeFn?
optionaldoctypeFn?: (value,currentElementName,currentElementObj) =>void
Custom processing hook called for each DOCTYPE value.
Parameters
value
string
currentElementName
string
currentElementObj
object
Returns
void
elementNameFn?
optionalelementNameFn?: (value,currentElementName,currentElementObj) =>void
Custom processing hook called for each element name.
Parameters
value
string
currentElementName
string
currentElementObj
object
Returns
void
fullTagEmptyElement?
optionalfullTagEmptyElement?:boolean
Whether to emit empty elements as full tag pairs (<a></a>) instead of self-closing (<a/>).
Default
falsefullTagEmptyElementFn?
optionalfullTagEmptyElementFn?: (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?
optionalindentAttributes?:boolean
Whether to print each attribute on its own indented line (when spaces is set).
Default
falseindentCdata?
optionalindentCdata?:boolean
Whether to write CData sections on a new indented line.
Default
falseindentInstruction?
optionalindentInstruction?:boolean
Whether to indent processing instructions onto their own line.
Default
falseindentText?
optionalindentText?:boolean
Whether to indent text nodes onto their own line when spaces is set.
Default
falseinstructionFn?
optionalinstructionFn?: (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?
optionalinstructionNameFn?: (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?
optionalnoQuotesForNativeAttributes?:boolean
Whether to omit quotes around attribute values that are native JS types (numbers, booleans).
Default
falsespaces?
optionalspaces?:number|string
Number of spaces (or a string like '\t') to use for indenting XML output.
Default
0textFn?
optionaltextFn?: (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?
optionaldecode?: (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?
optionaldecodeAsProperty?:CodecOptions<S>["decodeAsProperty"]
Defined in: src/xml/codec.ts:78
encode?
optionalencode?: (ctx,next) =>XMLElement
Defined in: src/xml/codec.ts:74
Parameters
ctx
RootEncodingContext<S>
next
() => XMLElement
Returns
encodeAsProperty?
optionalencodeAsProperty?:CodecOptions<S>["encodeAsProperty"]
Defined in: src/xml/codec.ts:79
inlineProperty?
optionalinlineProperty?:boolean
Defined in: src/xml/codec.ts:76
propertyMatch?
optionalpropertyMatch?:RegExp|CodecOptions<S>["propertyMatch"]
Defined in: src/xml/codec.ts:77
propertyTagname?
optionalpropertyTagname?:string|CodecOptions<S>["propertyTagname"]
Defined in: src/xml/codec.ts:75
tagname?
optionaltagname?:string|CodecOptions<S>["tagname"]
Defined in: src/xml/codec.ts:72
XMLCommentNode
XMLCommentNode =
z.infer<typeofZXMLCommentNode>
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<typeofZXMLElementNode>
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
toXMLString()
toXMLString(
instance,options?):string
Converts an instance to an XML string.
Parameters
instance
output<S>
options?
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<typeofZXMLTextNode>
Defined in: src/xml/xml-js.ts:20
XMLVoid
XMLVoid =
EmptyObj
Defined in: src/xml/xml-js.ts:44
Variables
DATA
constDATA: typeofDATA
Defined in: src/model.ts:10
Stores the raw data object on model instances.
xml
constxml: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
// ✅ 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
// ✅ 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
constXML: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
Returns
object
attributes?
optionalattributes?:Record<string,string>
elements?
optionalelements?: ({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?
optionalattributes?: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
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
options?
StringifyOptions = {}
Returns
string
ZXMLCommentNode
constZXMLCommentNode:ZodObject<{comment:ZodString;type:ZodLiteral<"comment">; },$strip>
Defined in: src/xml/xml-js.ts:16
ZXMLElementNode
constZXMLElementNode: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
constZXMLNode:z.ZodDiscriminatedUnion<[typeofZXMLElementNode, typeofZXMLCommentNode, typeofZXMLTextNode],"type">
Defined in: src/xml/xml-js.ts:25
ZXMLRoot
constZXMLRoot: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
constZXMLTextNode: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
Example
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 → decode → schema.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() → encode → XML.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?
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?
optionalattributes?:Record<string,string>
elements?
optionalelements?: ({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?
Returns
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
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
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" }) {}