DOMParser

DOMParser 可以将存储在字符串中的 XMLHTML 源代码解析为一个 DOM Document

注意:XMLHttpRequest 支持从URL可寻址资源解析XML和HTML,在其response 属性中返回Document

你可以使用XMLSerializer 接口执行相反的操作 - 将DOM树转换为XML或HTML源。

对于HTML文档,您还可以通过设置 Element.innerHTMLouterHTML 属性的值,将部分 DOM 替换为从HTML构建的新 DOM 树。还可以读取这些属性以获取对应于相应 DOM 子树的 HTML 片段。

语法

let domparser = new DOMParser()​​;

方法

DOMParser.parseFromString()

语法

let doc = domparser.parseFromString(string, mimeType)

返回值

基于 mimeType 参数,返回 DocumentXMLDocument 或其他文档类型。

参数

该方法接收 2 个必要参数:

string
要解析的 DOMString。它必须包含 HTMLxmlxhtml+xmlsvg 文档。
mimeType
一个 DOMString。This string determines a class of the the method's return value. The possible values are the following:
mimeType doc.constructor
text/html Document
text/xml XMLDocument
application/xml XMLDocument
application/xhtml+xml XMLDocument
image/svg+xml XMLDocument

解析 XML

一旦建立了一个解析对象以后,你就可以使用它的 parseFromString 方法来解析一个 XML 字符串:

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

错误处理

如果解析失败, DOMParser 不会抛出任何异常,而是会返回一个给定的错误文档:

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

解析错误会显示在错误控制台,包括文档的地址和错误的源代码。

解析 SVG 或者 HTML 文档

DOMParser 也可以用来解析 SVG 文档 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7) 或者 HTML 文档 (Firefox 12.0 / Thunderbird 12.0 / SeaMonkey 2.9)。根据给定的 MIME 类型不同,parseFromString 方法可能返回三种不同类型的文档。如果MIME类型是 text/xml,则返回一个 XMLDocument,如果 MIME 类型是 text/svg+xml,则返回一个 SVGDocument,如果MIME类型是 text/html,则返回一个 HTMLDocument

let parser = new DOMParser();
let doc = parser.parseFromString(stringContainingXMLSource, "application/xml");
// 返回一个 Document 对象,但不是 SVGDocument,也不是 HTMLDocument

parser = new DOMParser();
doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml");
// 返回一个 SVGDocument 对象,同时也是一个 Document 对象。

parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html")
// 返回一个 HTMLDocument 对象,同时也是一个 Document 对象。

DOMParser HTML 扩展

/*
 * 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));

规范

规范 状态 备注
DOM Parsing and Serialization
DOMParser
Working Draft Initial definition

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
DOMParserChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 9Opera Full support 8Safari Full support 3.2WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 2Samsung Internet Android Full support 1.0
DOMParser() constructorChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 9Opera Full support 8Safari Full support 3.2WebView Android Full support YesChrome Android Full support 18Firefox Android Full support YesOpera Android Full support YesSafari iOS ? Samsung Internet Android Full support 1.0
parseFromStringChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 9Opera Full support 8Safari Full support 3.2WebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
parseFromString: HTML (text/html) supportChrome Full support 31Edge Full support 12Firefox Full support 12IE Full support 10Opera Full support 17Safari Full support 9.1WebView Android Full support 37Chrome Android Full support 31Firefox Android Full support 14Opera Android ? Safari iOS ? Samsung Internet Android Full support 3.0
parseFromString: SVG (image/svg+xml) supportChrome Full support 4Edge Full support 12Firefox Full support 10IE Full support 10Opera Full support 15Safari Full support 3.2WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 10Opera Android Full support YesSafari iOS ? Samsung Internet Android Full support 1.0
parseFromString: XML (application/xml) supportChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 9Opera Full support 8Safari Full support 3.2WebView Android Full support YesChrome Android Full support 18Firefox Android Full support YesOpera Android Full support YesSafari iOS ? Samsung Internet Android Full support 1.0

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

参见