XMLSerializer - Web APIs | MDN

Constructor

XMLSerializer()

Creates a new XMLSerializer object.

Instance methods

serializeToString()

Returns the serialized subtree of a string.

Examples

Serializing XML into a string

This example just serializes an entire document into a string containing XML.

js

const s = new XMLSerializer();
const str = s.serializeToString(document);
saveXML(str);

This involves creating a new XMLSerializer object, then passing the Document to be serialized into serializeToString(), which returns the XML equivalent of the document. saveXML() represents a function that would then save the serialized string.

Inserting nodes into a DOM based on XML

This example uses the Element.insertAdjacentHTML() method to insert a new DOM Node into the body of the Document, based on XML created by serializing an Element object.

Because insertAdjacentHTML() accepts a string and not a Node as its second parameter, XMLSerializer is used to first convert the node into a string.

js

const inp = document.createElement("input");
const XMLS = new XMLSerializer();
const inpSerialized = XMLS.serializeToString(inp); // First convert DOM node into a string

// Insert the newly created node into the document's body
document.body.insertAdjacentHTML("afterbegin", inpSerialized);

The code creates a new <input> element by calling Document.createElement(), then serializes it into XML using serializeToString().

Once that's done, insertAdjacentHTML() is used to insert the <input> element into the DOM.

Specifications

Specification
HTML
# xmlserializer

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.