DOMParser - Web APIs 编辑

The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document.

Note: XMLHttpRequest can parse XML and HTML directly from a URL-addressable resource, returning a Document in its response property.

You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the XMLSerializer interface.

In the case of an HTML document, you can also replace portions of the DOM with new DOM trees built from HTML by setting the value of the Element.innerHTML and outerHTML properties. These properties can also be read to fetch HTML fragments corresponding to the corresponding DOM subtree.

Syntax

const domparser = new DOMParser()

Methods

DOMParser.parseFromString()

Syntax

const doc = domparser.parseFromString(string, mimeType)

Return

Either Document or XMLDocument depending on the mimeType argument.

Parameters

This method has 2 parameters (both required):

string
The DOMString to be parsed. It must contain either HTML, xml, xhtml+xml, or svg document.
mimeType

A DOMString. This string determines a class of the method's return value. The possible values are the following:

mimeTypedoc.constructor
text/htmlDocument
text/xmlXMLDocument
application/xmlXMLDocument
application/xhtml+xmlXMLDocument
image/svg+xmlXMLDocument

Examples

Parsing XML

Once you have created a parser object, you can parse XML from a string using the parseFromString() method:

let parser = new DOMParser()
let doc = parser.parseFromString(stringContainingXMLSource, "application/xml")

Error handling

Note that if the parsing process fails, the DOMParser does not throw an exception, but instead returns an error document:

<parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">
  (error description)
  <sourcetext>(a snippet of the source XML)</sourcetext>
</parsererror>

The parsing errors are also reported to the Error Console, with the document URI (see below) as the source of the error.

Parsing SVG or HTML

The DOMParser can also be used to parse an SVG document (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7) or an HTML document (Firefox 12.0 / Thunderbird 12.0 / SeaMonkey 2.9). There are three different results possible, selected by the MIME type given.

  1. If the MIME type is text/xml, the result will be an XMLDocument
  2. If the MIME type is image/svg+xml, the result will be an SVGDocument
  3. If the MIME type is text/html, the result will be an HTMLDocument
let parser = new DOMParser()
let doc = parser.parseFromString(stringContainingXMLSource, "application/xml")
// returns a Document, but not an SVGDocument nor an HTMLDocument

parser = new DOMParser();
doc = parser.parseFromString(stringContainingSVGSource, "image/svg+xml")
// returns a SVGDocument, which also is a Document.

parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html")
// returns an HTMLDocument, which also is a Document.

DOMParser HTML extension

/*
 * DOMParser HTML extension
 * 2012-09-04
 *
 * By Eli Grey, http://eligrey.com
 * Public domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 */

/*! @source https://gist.github.com/1129031 */
/*global document, DOMParser*/

(function(DOMParser) {
	"use strict";

	var proto = DOMParser.prototype,
	nativeParse = proto.parseFromString;

	// Firefox/Opera/IE throw errors on unsupported types
	try {
		// WebKit returns null on unsupported types
		if ((new DOMParser()).parseFromString("", "text/html")) {
			// text/html parsing is natively supported
			return;
		}
	} catch (ex) {}

	proto.parseFromString = function(markup, type) {
		if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
			var doc = document.implementation.createHTMLDocument("");
				if (markup.toLowerCase().indexOf('<!doctype') > -1) {
					doc.documentElement.innerHTML = markup;
				} else {
					doc.body.innerHTML = markup;
				}
			return doc;
		} else {
			return nativeParse.apply(this, arguments);
		}
	};
}(DOMParser));

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'DOM parsing' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

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

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

发布评论

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

词条统计

浏览:83 次

字数:8975

最后编辑:8年前

编辑次数:0 次

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