xmldoc: Lightweight XML Document Parser

2.0.3 · active · verified Sun Apr 19

xmldoc is a lightweight JavaScript library designed for parsing and traversing XML documents. It provides a simple, object-oriented API for interacting with XML structures, backed by the robust `sax` parser. The current stable version is 2.0.3, with releases occurring as needed for bug fixes and feature enhancements, rather than on a strict cadence. A key differentiator is its minimal footprint and direct access to XML elements and attributes, avoiding more complex XPath implementations by default. Since version 2.0, it fully supports TypeScript, offering type definitions for a better developer experience, and is compatible with both CommonJS and ESM environments. It focuses on parsing and basic traversal, making it suitable for applications where full XML DOM manipulation or complex querying (like advanced XPath) is not required.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing an XML string, traversing elements, accessing attributes and text content, and converting the document back to a string.

import { XmlDocument, XmlElement } from "xmldoc";

const xmlString = `
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
    <!-- A comment about Italian cuisine -->
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J.K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <magazine>
    <title>National Geographic</title>
  </magazine>
</bookstore>
`;

// Parse the XML string
const document = new XmlDocument(xmlString);

// Find all books
const books = document.childrenNamed("book");
console.log(`Found ${books.length} books.`);

// Access attributes and text content of the first book
const firstBook = books[0];
if (firstBook) {
  console.log(`First book title: ${firstBook.childNamed("title")?.val} (Lang: ${firstBook.childNamed("title")?.attr.lang})`);
  console.log(`First book author: ${firstBook.childNamed("author")?.val}`);
  console.log(`First book category: ${firstBook.attr.category}`);
}

// Find a specific element by path
const harryPotterTitle = document.childNamed("bookstore")
                                  ?.childrenNamed("book")
                                  .find(book => book.childNamed("title")?.val === "Harry Potter")
                                  ?.childNamed("title");

if (harryPotterTitle) {
  console.log(`Harry Potter title found: ${harryPotterTitle.val}`);
}

// Convert back to string (note: comments might be lost depending on version)
const serializedXml = document.toString({ compressed: true }); // compressed option for brevity
console.log("Serialized XML (compressed):", serializedXml.substring(0, 100) + "..."); // show first 100 chars

view raw JSON →