The XMLSerializer
interface provides the serializeToString()
method to construct an XML string representing a DOM tree.
serializeToString()
serializeToStream()
The first, basic, example just serializes an entire document into a string containing XML.
var s = new XMLSerializer(); var d = document; var str = s.serializeToString(d); 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.
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.
Note: In the real world, you should usually instead call importNode()
method to import the new node into the DOM, then call one of the following methods to add the node to the DOM tree:
Document
and Element
methods append()
and prepend()
Node.replaceWith()
method (to replace an existing node with the new one)Document.insertAdjacentElement()
and Element.insertAdjacentElement()
methods.Because insertAdjacentHTML()
accepts a string and not a Node
as its second parameter, XMLSerializer
is used to first convert the node into a string.
var inp = document.createElement('input'); var XMLS = new XMLSerializer(); var inp_xmls = XMLS.serializeToString(inp); // First convert DOM node into a string // Insert the newly created node into the document's body document.body.insertAdjacentHTML('afterbegin', inp_xmls);
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.
Specification | Status | Comment |
---|---|---|
DOM Parsing and Serialization The definition of 'XMLSerializer' in that specification. | Working Draft |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | Yes | Yes | 9 | Yes | 3 |
serializeToStream
|
Yes | No | ? — 20 | No | Yes | No |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | Yes | Yes | ? | Yes |
serializeToStream
|
Yes | Yes | No | ? — 20 | Yes | No | Yes |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/XMLSerializer