What is w3c-xmlserializer?
The w3c-xmlserializer npm package is used to serialize DOM nodes to XML strings, following the W3C specification. It is typically used to convert DOM trees into a format that can be easily transported or stored.
What are w3c-xmlserializer's main functionalities?
Serializing DOM Nodes
This feature allows you to serialize a DOM node (such as an entire document or an individual element) to a string that contains XML. The code sample demonstrates how to create an instance of XMLSerializer and use it to serialize a DOM document to an XML string.
const { XMLSerializer } = require('w3c-xmlserializer');
const serializer = new XMLSerializer();
const xmlString = serializer.serializeToString(document);
Other packages similar to w3c-xmlserializer
xmlserializer
The xmlserializer package provides similar functionality to w3c-xmlserializer, allowing for the serialization of DOM nodes to XML strings. It may differ in implementation details or API design.
xmldom
xmldom is a package that not only allows for serialization of DOM nodes but also includes a DOM parser for XML. This makes it a more comprehensive tool for working with XML in JavaScript, compared to w3c-xmlserializer which focuses only on serialization.
xml-js
xml-js is a package that can convert XML text to a JavaScript object and vice versa. It provides a different approach compared to w3c-xmlserializer by offering a JSON-like experience when working with XML.
w3c-xmlserializer
An XML serializer that follows the W3C specification.
This package can be used in Node.js, as long as you feed it a DOM node, e.g. one produced by jsdom.
Basic usage
Assume you have a DOM tree rooted at a node node
. In Node.js, you could create this using jsdom as follows:
const { JSDOM } = require("jsdom");
const { document } = new JSDOM().window;
const node = document.createElement("akomaNtoso");
Then, you use this package as follows:
const serialize = require("w3c-xmlserializer");
console.log(serialize(node));
requireWellFormed
option
By default the input DOM tree is not required to be "well-formed"; any given input will serialize to some output string. You can instead require well-formedness via
serialize(node, { requireWellFormed: true });
which will cause Error
s to be thrown when non-well-formed constructs are encountered. Per the spec, this largely is about imposing constraints on the names of elements, attributes, etc.
As a point of reference, on the web platform:
- The
innerHTML
getter uses the require-well-formed mode, i.e. trying to get the innerHTML
of non-well-formed subtrees will throw. - The
xhr.send()
method does not require well-formedness, i.e. sending non-well-formed Document
s will serialize and send them anyway.