Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. XMLSerializer

XMLSerializer

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

TheXMLSerializer interface provides theserializeToString() method to construct an XML string representing aDOM tree.

Note:The resulting XML string is not guaranteed to be well-formed XML.

Constructor

XMLSerializer()

Creates a newXMLSerializer 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 newXMLSerializer object, then passing theDocument to be serialized intoserializeToString(), 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 theElement.insertAdjacentHTML() method to insert a new DOMNode into the body of theDocument, based on XML created by serializing anElement object.

Note:In the real world, you should usually instead callimportNode() method to import the new node into the DOM, then call one of the following methods to add the node to the DOM tree:

BecauseinsertAdjacentHTML() accepts a string and not aNode 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 inp_xmls = XMLS.serializeToString(inp); // First convert DOM node into a string// Insert the newly created node into the document's bodydocument.body.insertAdjacentHTML("afterbegin", inp_xmls);

The code creates a new<input> element by callingDocument.createElement(), then serializes it into XML usingserializeToString().

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 byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp