npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cerios/xml-poto

v2.6.0

Published

TypeScript XML serialization library with decorator-based metadata. Supports namespaces, custom converters, validation, wrapped/unwrapped arrays, and bidirectional XML-object mapping.

Readme

@cerios/xml-poto

A powerful TypeScript XML serialization library with decorator-based metadata. Provides type-safe, bidirectional XML-object mapping with support for namespaces, custom converters, validation, and flexible array handling.

npm version npm downloads License: MIT TypeScript

✨ Key Features

  • 🎯 Type-Safe - Full TypeScript support with compile-time validation
  • 🔄 Bidirectional - Seamless XML ↔ Object conversion
  • 🏷️ Decorator-Based - Clean, declarative syntax
  • 🔍 Powerful Query API - XPath-like querying with fluent interface
  • ✏️ Dynamic XML Manipulation - Add, update, delete elements at runtime
  • 🔁 Full Serialization - Parse, modify, and serialize back to XML
  • 🌐 Namespace Support - Complete XML namespace handling
  • Validation - Pattern matching, enums, and required fields
  • 🔧 Extensible - Custom converters and transformations
  • 📦 Zero Config - Sensible defaults, extensive customization

📦 Installation

npm install @cerios/xml-poto

As a Dev Dependency

npm install --save-dev @cerios/xml-poto

Note: This package uses standard TypeScript decorators and does not require experimentalDecorators or emitDecoratorMetadata in your tsconfig.json. It works with modern TypeScript configurations out of the box.

🎯 Quick Start

import { XmlRoot, XmlElement, XmlAttribute, XmlSerializer } from "@cerios/xml-poto";

// 1. Define your class with decorators
@XmlRoot({ name: "Person" })
class Person {
	@XmlAttribute({ name: "id" })
	id: string = "";

	@XmlElement({ name: "Name" })
	name: string = "";

	@XmlElement({ name: "Email" })
	email: string = "";

	@XmlElement({ name: "Age" })
	age?: number;
}

// 2. Create serializer
const serializer = new XmlSerializer();

// 3. Serialize to XML
const person = new Person();
person.id = "123";
person.name = "John Doe";
person.email = "[email protected]";
person.age = 30;

const xml = serializer.toXml(person);
console.log(xml);
// Output:
// <?xml version="1.0" encoding="UTF-8"?>
// <Person id="123">
//   <Name>John Doe</Name>
//   <Email>[email protected]</Email>
//   <Age>30</Age>
// </Person>

// 4. Deserialize from XML
const xmlString = `
    <Person id="456">
        <Name>Jane Smith</Name>
        <Email>[email protected]</Email>
        <Age>25</Age>
    </Person>
`;

const deserializedPerson = serializer.fromXml(xmlString, Person);
console.log(deserializedPerson);
// Output: Person { id: '456', name: 'Jane Smith', email: '[email protected]', age: 25 }

🔁 Bi-directional XML (XmlDynamic)

Parse XML, modify it dynamically, and serialize back - perfect for XML transformation workflows:

import { XmlRoot, XmlDynamic, DynamicElement, XmlQuery, XmlSerializer } from "@cerios/xml-poto";

@XmlRoot({ name: "Catalog" })
class Catalog {
	@XmlDynamic()
	dynamic!: DynamicElement;
}

const xml = `
  <Catalog>
    <Product id="1"><Name>Laptop</Name><Price>999</Price></Product>
    <Product id="2"><Name>Mouse</Name><Price>29</Price></Product>
  </Catalog>
`;

const catalog = serializer.fromXml(xml, Catalog);

// Query and modify
const query = new XmlQuery([catalog.dynamic]);
query.find("Product").whereValueGreaterThan(100).setAttr("premium", "true");

// Add new elements
catalog.dynamic
	.createChild({
		name: "Product",
		attributes: { id: "3" },
	})
	.createChild({ name: "Name", text: "Keyboard" });

// Serialize back to XML
const updatedXml = catalog.dynamic.toXml({ indent: "  " });

See Bi-directional XML Guide for complete documentation.

Note: DynamicElement and @XmlDynamic are the current names for this feature.

📖 Documentation

Getting Started

Core Features

Advanced Features

🎯 Common Use Cases

| Use Case | Feature | Documentation | | ---------------------- | -------------------------- | ------------------------------------------------- | | REST API XML responses | Basic serialization | Getting Started | | Configuration files | Nested objects, validation | Nested Objects | | RSS/Atom feeds | Unwrapped arrays | Arrays | | SOAP services | Namespaces | Namespaces | | Blog content | Mixed content, CDATA | Mixed Content | | Data extraction | Query API, XPath | Querying | | Code documentation | CDATA, comments | Text Content |

🔧 Decorator Overview

| Decorator | Purpose | Example | | --------------- | -------------------------------- | ----------------------------------------- | | @XmlRoot | Define root element | @XmlRoot({ name: 'Person' }) | | @XmlElement | Map to element | @XmlElement({ name: 'Name' }) | | @XmlAttribute | Map to attribute | @XmlAttribute({ name: 'id' }) | | @XmlText | Map to text content | @XmlText() | | @XmlComment | Add XML comments | @XmlComment({ targetProperty: 'name' }) | | @XmlArray | Configure arrays | @XmlArray({ itemName: 'Item' }) | | @XmlDynamic | Enable query API | @XmlDynamic() | | @XmlType | Declare schema type identity | @XmlType({ name: 'AddressType' }) | | @XmlInclude | Register subtypes for xsi:type | @XmlInclude(() => Circle) | | @XmlIgnore | Exclude a property | @XmlIgnore() |

💡 Why xml-poto?

Traditional Approach ❌

// Manual XML construction - error-prone
const xml = `<Person id="${id}"><Name>${name}</Name></Person>`;

// Manual parsing - tedious
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "text/xml");
const name = doc.querySelector("Name")?.textContent;

With xml-poto ✅

// Type-safe, automatic, validated
const xml = serializer.toXml(person);
const person = serializer.fromXml(xml, Person);

Benefits:

  • ✅ Type safety at compile-time
  • ✅ Automatic validation
  • ✅ No string concatenation
  • ✅ Bidirectional mapping
  • ✅ IDE autocomplete

📝 Feature Highlights

Query API - Extract Data with Ease

@XmlRoot({ name: "Catalog" })
class Catalog {
	@XmlDynamic() // Lazy-loaded and cached by default
	query!: DynamicElement;
}

const catalog = serializer.fromXml(xmlString, Catalog);

// Use XPath-like queries (DynamicElement built on first access)
const titles = catalog.query.find("Product").find("Title").texts();
const expensiveItems = catalog.query.find("Product").whereValueGreaterThan(100);

// Navigate the tree
const parent = catalog.query.children[0].parent;
const siblings = catalog.query.children[0].siblings;

Learn more about Querying →

Arrays - Flexible Collection Handling

// Wrapped array
@XmlArray({ containerName: 'Books', itemName: 'Book', type: Book })
books: Book[] = [];
// <Books><Book>...</Book><Book>...</Book></Books>

// Unwrapped array
@XmlArray({ itemName: 'Item', type: Item })
items: Item[] = [];
// <Item>...</Item><Item>...</Item>

Learn more about Arrays →

Recursive & Circular Types - Lazy Type References

The type option also accepts a () => Constructor thunk. Use it whenever the referenced class is not declared yet at decoration time — self-recursive types, mutually referencing classes, or a class declared later in the same file:

@XmlElement({ name: "Section" })
class Section {
	@XmlElement({ name: "Title" })
	title: string = "";

	// Direct `type: Section` would throw — the class binding isn't initialized yet
	@XmlArray({ itemName: "Section", type: () => Section })
	children?: Section[];
}

The thunk is resolved lazily on first use during (de)serialization.

Namespaces - Full XML Namespace Support

const ns = { uri: "http://example.com/schema", prefix: "ex" };

@XmlRoot({ name: "Document", namespace: ns })
class Document {
	@XmlElement({ name: "Title", namespace: ns })
	title: string = "";
}
// <ex:Document xmlns:ex="http://example.com/schema">
//   <ex:Title>...</ex:Title>
// </ex:Document>

Learn more about Namespaces →

Mixed Content - HTML-like Structures

@XmlRoot({ name: "Article" })
class Article {
	@XmlElement({ name: "Content", mixedContent: true })
	content: any;
}
// Handles: <Content>Text <em>emphasis</em> more text</Content>

Learn more about Mixed Content →

Validation - Enforce Data Integrity

All XSD facets are available on @XmlElement, @XmlAttribute, @XmlText, and @XmlArray, and are checked during both serialization and deserialization:

@XmlAttribute({
    name: 'email',
    required: true,
    pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
})
email: string = '';

@XmlElement({
    name: 'status',
    enumValues: ['active', 'inactive', 'pending']
})
status: string = '';

@XmlElement({ name: 'score', minInclusive: 0, maxInclusive: 100 })
score: number = 0;

@XmlElement({ name: 'sizes', list: { itemType: 'number' } })
sizes: number[] = []; // <sizes>1 2 3</sizes>

// Exclusive xs:choice: at most one of email/phone may be set
@XmlElement({ name: 'phone', choiceGroup: 'contact', choiceRequired: true })
phone?: string;

Control how violations are handled with the unified validationMode option — 'strict' (throw, default), 'warn' (console warning), or 'off' — and tune individual rules with validationModeOverrides:

const serializer = new XmlDecoratorSerializer({
	validationMode: "strict", // default for all rules
	validationModeOverrides: {
		pattern: "warn", // pattern violations only warn
		fixedValue: "off", // fixed-value checks skipped
		choiceGroup: "warn",
	},
});

Also supported: length/minLength/maxLength, minExclusive/maxExclusive, totalDigits/fractionDigits, whiteSpace normalization, fixedValue constraints, minOccurs/maxOccurs on arrays, and xsi:nil round-trips for isNullable properties.

Learn more about Validation →

Custom Converters - Transform Values

const dateConverter = {
    serialize: (date: Date) => date.toISOString(),
    deserialize: (str: string) => new Date(str)
};

// Elements take `transform`; attributes and text take `converter`
@XmlElement({ name: 'CreatedAt', transform: dateConverter })
createdAt: Date = new Date();

@XmlAttribute({ name: 'updatedAt', converter: dateConverter })
updatedAt: Date = new Date();

Learn more about Converters → · Transform →

🎓 Best Practices

  1. Initialize properties: Always provide default values

    name: string = ""; // ✅ Good
    name: string; // ❌ May cause issues
  2. Specify types for arrays: Use the type parameter for complex objects

    @XmlArray({ itemName: 'Item', type: Item })
    items: Item[] = [];
  3. Use validation for external data: Apply required, pattern, enum for untrusted XML

    @XmlAttribute({ name: 'id', required: true, pattern: /^\d+$/ })
    id: string = '';
  4. Test round-trip serialization: Verify data integrity

    const xml = serializer.toXml(original);
    const restored = serializer.fromXml(xml, MyClass);

🆚 Comparison

| Feature | xml-poto | Manual Parsing | Other Libraries | | ------------- | ------------- | -------------- | --------------- | | Type Safety | ✅ Full | ❌ None | ⚠️ Partial | | Bidirectional | ✅ Yes | ❌ No | ✅ Yes | | Decorators | ✅ Yes | ❌ No | ⚠️ Some | | Query API | ✅ XPath-like | ❌ No | ❌ No | | Namespaces | ✅ Full | ⚠️ Manual | ⚠️ Limited | | Validation | ✅ Built-in | ❌ Manual | ⚠️ External | | Mixed Content | ✅ Yes | ⚠️ Complex | ❌ No |

🛠️ Document-Level Options

Processing instructions, DOCTYPE declarations, empty-element syntax and output formatting are SerializationOptions passed to the serializer:

const serializer = new XmlSerializer({
	processingInstructions: [{ target: "xml-stylesheet", data: 'type="text/xsl" href="s.xsl"' }],
	docType: { rootElement: "doc", systemId: "http://example.com/doc.dtd" },
	emptyElementStyle: "explicit", // <tag></tag> instead of <tag/>
	format: false, // compact, single-line output
});

🤝 Contributing

Contributions are welcome! Please open an issue or pull request on GitHub.

📄 License

MIT © Ronald Veth - Cerios

🔗 Links


Next Steps: