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

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

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

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

创建一个DOMParser

要创建一个DOMParser对象,只需使用 new DOMParser()

解析 XML

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

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

错误处理

如果解析失败, DOMParser 目前不会抛出任何异常, 只会返回一个给定的错误文档(查看 bug 45566):

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

规范

Specification Status Comment
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 YesFirefox 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 ?
DOMParser() constructorChrome Full support 1Edge Full support YesFirefox 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 ?
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 ?
parseFromString: XML (application/xml) supportChrome Full support 1Edge Full support YesFirefox 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 ?
parseFromString: SVG (image/svg+xml) supportChrome Full support 4Edge Full support YesFirefox 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 ?
parseFromString: HTML (text/html) supportChrome Full support 31Edge Full support YesFirefox 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 ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

参见

文档标签和贡献者

标签: 
最后编辑者: mdnwebdocs-bot,