XMLSerializer - Web APIs 编辑

The XMLSerializer interface provides the serializeToString() method to construct an XML string representing a DOM tree.

Methods

serializeToString()
Returns the serialized subtree of a string.
serializeToStream() This API has not been standardized.This deprecated API should no longer be used, but will probably still work.
The subtree rooted by the specified element is serialized to a byte stream using the character set specified.

Examples

Serializing XML into a string

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.

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.

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:

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.

Specifications

SpecificationStatusComment
DOM Parsing and Serialization
The definition of 'XMLSerializer' in that specification.
Working Draft 

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:75 次

字数:7146

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文