--- title: DOMParser slug: Web/API/DOMParser tags: - API - DOM - DOM Parsing - Document - XML - 参考 translation_of: Web/API/DOMParser --- <div>{{APIRef("DOM")}}</div> <p><strong><code>DOMParser</code></strong> 可以将存储在字符串中的 {{Glossary("XML")}} 或 {{Glossary("HTML")}} 源代码解析为一个 DOM {{domxref("Document")}}。</p> <div class="note"> <p><strong>注意:</strong>{{domxref("XMLHttpRequest")}} 支持从URL可寻址资源解析XML和HTML,在其{{domxref("XMLHttpRequest.response", "response")}} 属性中返回<code>Document</code>。</p> </div> <p>你可以使用{{domxref("XMLSerializer")}} 接口执行相反的操作 - 将DOM树转换为XML或HTML源。</p> <p>对于HTML文档,您还可以通过设置 {{domxref("Element.innerHTML")}} 和{{domxref("Element.outerHTML", "outerHTML")}} 属性的值,将部分 DOM 替换为从HTML构建的新 DOM 树。还可以读取这些属性以获取对应于相应 DOM 子树的 HTML 片段。</p> <h2 id="语法">语法</h2> <pre class="brush: js">let <em>domparser</em> = new DOMParser();</pre> <h2 class="brush: js" id="方法">方法</h2> <p>{{domxref("DOMParser.parseFromString()")}}</p> <h3 id="语法_2">语法</h3> <pre class="brush: js"><em>let </em><strong>doc</strong><em><strong> </strong>= domparser.</em>parseFromString(<em>string</em>, <em>mimeType</em>)</pre> <h3 id="返回值">返回值</h3> <p>基于 <strong><code><a href="#Argument02">mimeType</a></code></strong> 参数,返回 {{domxref("Document")}} 或 {{domxref("XMLDocument")}} 或其他文档类型。</p> <h3 id="参数">参数</h3> <p>该方法接收 2 个必要参数:</p> <dl> <dt><code>string</code></dt> <dd>要解析的 {{domxref("DOMString")}}。它必须包含 {{Glossary("HTML")}}、{{Glossary("xml")}}、{{Glossary("xhtml+xml")}} 或 {{Glossary("svg")}} 文档。</dd> <dt><a id="Argument02"></a></dt> <dt><code>mimeType</code></dt> </dl> <dl> <dd>一个 {{domxref("DOMString")}}。This string determines a class of the the method's return value. The possible values are the following:</dd> </dl> <table class="standard-table" style="max-width: 50%;"> <thead> <tr> <th scope="col"><code>mimeType</code></th> <th scope="col">doc.constructor</th> </tr> </thead> <tbody> <tr> <td><code>text/html</code></td> <td><code>{{domxref("Document")}}</code></td> </tr> <tr> <td><code>text/xml</code></td> <td><code>{{domxref("XMLDocument")}}</code></td> </tr> <tr> <td><code>application/xml</code></td> <td><code>{{domxref("XMLDocument")}}</code></td> </tr> <tr> <td><code>application/xhtml+xml</code></td> <td><code>{{domxref("XMLDocument")}}</code></td> </tr> <tr> <td><code>image/svg+xml</code></td> <td><code>{{domxref("XMLDocument")}}</code></td> </tr> </tbody> </table> <h2 id="解析_XML">解析 XML</h2> <p>一旦建立了一个解析对象以后,你就可以使用它的 <code>parseFromString</code> 方法来解析一个 XML 字符串:</p> <pre class="brush: js">let parser = new DOMParser(), doc = parser.parseFromString(stringContainingXMLSource, "application/xml"); </pre> <h4 id="错误处理">错误处理</h4> <p>如果解析失败, <code>DOMParser</code> 不会抛出任何异常,而是会返回一个给定的错误文档:</p> <pre class="brush:xml"><parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml"> (error description) <sourcetext>(a snippet of the source XML)</sourcetext> </parsererror> </pre> <p>解析错误会显示在<a href="../../../zh-cn/Error_Console">错误控制台</a>,包括文档的地址和错误的源代码。</p> <h2 id="解析_SVG_或者_HTML_文档">解析 SVG 或者 HTML 文档</h2> <p><code>DOMParser</code> 也可以用来解析 SVG 文档 {{geckoRelease("10.0")}} 或者 HTML 文档 {{geckoRelease("12.0")}}。根据给定的 MIME 类型不同,<code>parseFromString</code> 方法可能返回三种不同类型的文档。如果MIME类型是 <code>text/xml</code>,则返回一个 <code>XMLDocument</code>,如果 MIME 类型是 <code>text/svg+xml</code>,则返回一个 <code>SVGDocument</code>,如果MIME类型是 <code>text/html</code>,则返回一个 <code>HTMLDocument</code>。</p> <pre class="brush: js">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 对象。 </pre> <h2 id="DOMParser_HTML_扩展">DOMParser HTML 扩展</h2> <pre class="brush: js">/* * 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));</pre> <h2 id="规范">规范</h2> <table class="standard-table"> <thead> <tr> <th scope="col">规范</th> <th scope="col">状态</th> <th scope="col">备注</th> </tr> </thead> <tbody> <tr> <td>{{SpecName('DOM Parsing', '#the-domparser-interface', 'DOMParser')}}</td> <td>{{Spec2('DOM Parsing')}}</td> <td>Initial definition</td> </tr> </tbody> </table> <h2 id="浏览器兼容性">浏览器兼容性</h2> <p>{{Compat("api.DOMParser", 3)}}</p> <h2 id="参见">参见</h2> <ul> <li><a href="/en-US/docs/Parsing_and_serializing_XML">Parsing and serializing XML</a></li> <li>{{domxref("XMLHttpRequest")}}</li> <li>{{domxref("XMLSerializer")}}</li> <li>{{jsxref("JSON.parse()")}} - counterpart for {{jsxref("JSON")}} documents.</li> </ul>