xml-model
v2.0.0
Published
allows transparent XML <-> Object conversion in typescript
Readme
XML Model
Installation
xml-model requires Zod v4 as a peer dependency.
npm install xml-model zodWhat is xml-model?
xml-model lets you define TypeScript classes that map directly to XML documents using Zod schemas. Annotate fields with xml.attr() for XML attributes, or use xml.prop() when you need to customise a child element's tagname, inline mode, or matching — plain Zod schemas work as-is for regular child elements. Then parse or serialise with a single method call.
import { z } from "zod";
import { xmlModel, xml } from "xml-model";
class Book extends xmlModel(
z.object({
isbn: xml.attr(z.string(), { name: "isbn" }),
title: z.string(),
year: z.number(),
}),
{ tagname: "book" },
) {
label() {
return `${this.title} (${this.year})`;
}
}
// XML → class instance
const book = Book.fromXML(`
<book isbn="978-0-7432-7356-5">
<title>Dune</title>
<year>1965</year>
</book>
`);
book.label(); // "Dune (1965)"
book instanceof Book; // true
// class instance → XML string
Book.toXMLString(book);
// <book isbn="978-0-7432-7356-5"><title>Dune</title><year>1965</year></book>Field names are automatically converted to kebab-case XML tags (publishedAt → <published-at>). Extend classes with .extend() to build inheritance hierarchies — child instances remain instanceof the parent and inherit all methods.
