🚀. Socket Launch Week Day 3:Socket Firewall Now Blocks Malicious VS Code and Open VSX Extensions.Learn more
Sign In

@cerios/xml-poto

Package Overview
Dependencies
Maintainers
2
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cerios/xml-poto

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

latest
Source
npmnpm
Version
2.3.2
Version published
Maintainers
2
Created
Source

@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({ elementName: "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 = "john@example.com";
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>john@example.com</Email>
//   <Age>30</Age>
// </Person>

// 4. Deserialize from XML
const xmlString = `
    <Person id="456">
        <Name>Jane Smith</Name>
        <Email>jane@example.com</Email>
        <Age>25</Age>
    </Person>
`;

const deserializedPerson = serializer.fromXml(xmlString, Person);
console.log(deserializedPerson);
// Output: Person { id: '456', name: 'Jane Smith', email: 'jane@example.com', 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({ elementName: "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: Use DynamicElement and @XmlDynamic for new code. DynamicElement and @XmlDynamic are deprecated but still supported.

📖 Documentation

Getting Started

Core Features

Advanced Features

Reference

Examples

🎯 Common Use Cases

Use CaseFeatureDocumentation
REST API XML responsesBasic serializationGetting Started
Configuration filesNested objects, validationNested Objects
RSS/Atom feedsUnwrapped arraysArrays
SOAP servicesNamespacesNamespaces
Blog contentMixed content, CDATAMixed Content
Data extractionQuery API, XPathQuerying
Code documentationCDATA, commentsCDATA

🔧 Decorator Overview

DecoratorPurposeExample
@XmlRootDefine root element@XmlRoot({ elementName: 'Person' })
@XmlElementMap to element@XmlElement({ name: 'Name' })
@XmlAttributeMap to attribute@XmlAttribute({ name: 'id' })
@XmlTextMap to text content@XmlText()
@XmlCommentAdd XML comments@XmlComment()
@XmlArrayConfigure arrays@XmlArray({ itemName: 'Item' })
@XmlDynamicEnable query API@XmlDynamic()

Full API Reference →

💡 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({ elementName: "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 →

Namespaces - Full XML Namespace Support

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

@XmlRoot({ elementName: "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({ elementName: "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

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

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

Learn more about Validation →

Custom Converters - Transform Values

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

@XmlElement({ name: 'CreatedAt', converter: dateConverter })
createdAt: Date = new Date();

Learn more about Converters →

🎓 Best Practices

  • Initialize properties: Always provide default values

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

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

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

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

🆚 Comparison

Featurexml-potoManual ParsingOther 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

🛠️ Advanced Topics

🤝 Contributing

Contributions are welcome! Please see our Contributing Guide.

📄 License

MIT © Ronald Veth - Cerios

Next Steps:

Keywords

bi-directional

FAQs

Package last updated on 09 Jun 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts