Parsing and serializing XML - Developer guides 编辑

At times, you may need to parse XML content and convert it into a DOM tree, or, conversely, serialize an existing DOM tree into XML. In this article, we'll look at the objects provided by the web platform to make the common tasks of serializing and parsing XML easy.

XMLSerializer
Serializes DOM trees, converting them into strings containing XML.
DOMParser
Constructs a DOM tree by parsing a string containing XML, returning a XMLDocument or Document as appropriate based on the input data.
XMLHttpRequest
Loads content from a URL; XML content is returned as an XML Document object with a DOM tree built from the XML itself.
XPath
A technology for creating strings that contain addresses for specific portions of an XML document, and locating XML nodes based on those addresses.

Creating an XML document

Using one of the following approaches to create an XML document (which is an instance of Document.

Parsing strings into DOM trees

This example converts an XML fragment in a string into a DOM tree using a DOMParser:

const xmlStr = '<a id="a"><b id="b">hey!</b></a>';
const parser = new DOMParser();
const dom = parser.parseFromString(xmlStr, "application/xml");
// print the name of the root element or error message
console.log(dom.documentElement.nodeName == "parsererror" ? "error while parsing" : dom.documentElement.nodeName);

Parsing URL-addressable resources into DOM trees

Using XMLHttpRequest

Here is sample code that reads and parses a URL-addressable XML file into a DOM tree:

const xhr = new XMLHttpRequest();

xhr.onload = function() {
  dump(xhr.responseXML.documentElement.nodeName);
}

xhr.onerror = function() {
  dump("Error while getting XML.");
}

xhr.open("GET", "example.xml");
xhr.responseType = "document";
xhr.send();

The value returned in the xhr object's responseXML field is a Document constructed by parsing the XML.

If the document is HTML, the code shown above will return a Document. If the document is XML, the resulting object is actually a XMLDocument. The two types are essentially the same; the difference is largely historical, although differentiating has some practical benefits as well.

Note: There is in fact an HTMLDocument interface as well, but it is not necessarily an independent type. In some browsers it is, while in others it is an alias for the Document interface.

Serializing an XML document

Given a Document, you can serialize the document's DOM tree back into XML using the XMLSerializer.serializeToString() method.

Use the following approaches to serialize the contents of the XML document you created in the previous section.

Serializing DOM trees to strings

First, create a DOM tree as described in How to Create a DOM tree. Alternatively, use a DOM tree obtained from XMLHttpRequest.

To serialize the DOM tree doc into XML text, call XMLSerializer.serializeToString():

const serializer = new XMLSerializer();
const xmlStr = serializer.serializeToString(doc);

Serializing HTML documents

If the DOM you have is an HTML document, you can serialize using serializeToString(), but there is a simpler option: just use the Element.innerHTML property (if you want just the descendants of the specified node) or the Element.outerHTML property if you want the node and all its descendants.

const docInnerHtml = document.documentElement.innerHTML;

As a result, docHTML is a DOMString containing the HTML of the contents of the document; that is, the <body> element's contents.

You can get HTML corresponding to the <body> and its descendants with this code:

const docOuterHtml = document.documentElement.outerHTML;

See also

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

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

发布评论

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

词条统计

浏览:103 次

字数:7317

最后编辑:7年前

编辑次数:0 次

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