XMLSerializer 接口提供 serializeToString() 方法以构造 XML 字符串表示 DOM 树。

方法

serializeToString()

返回字符串的序列化子树。

serializeToStream()

The subtree rooted by the specified element is serialized to a byte stream using the character set specified.

范例

把 XML 序列化成字符串

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.

把节点插入基于 XML 的 DOM 中

此范例使用 Element.insertAdjacentHTML() method to insert a new DOM 节点 into the body of the Document , based on XML created by serializing an 元素 对象。

注意: 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:

因为 insertAdjacentHTML() accepts a string and not a 节点 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.

规范

规范 状态 注释
DOM 剖析和序列化
在该规范中的 XMLSerializer 定义。
工作草案

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
XMLSerializer Chrome Yes Edge 12 Firefox Yes IE 9 Opera Yes Safari 3 WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
serializeToStream 弃用 非标 Chrome Yes Edge 79 Firefox 不支持 ? — 20 IE 不支持 No Opera Yes Safari 不支持 No WebView Android Yes Chrome Android Yes Firefox Android 不支持 ? — 20 Opera Android Yes Safari iOS 不支持 No Samsung Internet Android Yes

图例

完整支持

完整支持

不支持

不支持

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

非标。预期跨浏览器支持较差。

弃用。不要用于新网站。

弃用。不要用于新网站。

另请参阅

元数据

  • 最后修改:
  1. XMLSerializer