【发布时间】:2012-07-18 19:08:53
【问题描述】:
似乎所有主流浏览器都实现了 DOMParser API,以便可以将 XML 解析为 DOM,然后使用 XPath、getElementsByTagName 等进行查询...
但是,检测解析错误似乎比较棘手。 DOMParser.prototype.parseFromString 总是返回一个有效的 DOM。发生解析错误时,返回的 DOM 包含 <parsererror> 元素,但在各个主流浏览器中略有不同。
示例 JavaScript:
xmlText = '<root xmlns="http://default" xmlns:other="http://other"><child><otherr:grandchild/></child></root>';
parser = new DOMParser();
dom = parser.parseFromString(xmlText, 'application/xml');
console.log((new XMLSerializer()).serializeToString(dom));
Opera 中的结果:
DOM 的根是 <parsererror> 元素。
<?xml version="1.0"?><parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">Error<sourcetext>Unknown source</sourcetext></parsererror>
Firefox 中的结果:
DOM 的根是 <parsererror> 元素。
<?xml-stylesheet href="chrome://global/locale/intl.css" type="text/css"?>
<parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">XML Parsing Error: prefix not bound to a namespace
Location: http://fiddle.jshell.net/_display/
Line Number 1, Column 64:<sourcetext><root xmlns="http://default" xmlns:other="http://other"><child><otherr:grandchild/></child></root>
---------------------------------------------------------------^</sourcetext></parsererror>
Safari 中的结果:
<root> 元素解析正确,但在与 Opera 和 Firefox 的 <parsererror> 元素不同的命名空间中包含嵌套的 <parsererror>。
<root xmlns="http://default" xmlns:other="http://other"><parsererror xmlns="http://www.w3.org/1999/xhtml" style="display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black"><h3>This page contains the following errors:</h3><div style="font-family:monospace;font-size:12px">error on line 1 at column 50: Namespace prefix otherr on grandchild is not defined
</div><h3>Below is a rendering of the page up to the first error.</h3></parsererror><child><otherr:grandchild/></child></root>
我是否缺少一种简单的跨浏览器检测 XML 文档中是否出现解析错误的方法?或者我必须为不同浏览器可能生成的每个可能的<parsererror> 元素查询 DOM?
【问题讨论】:
-
你能在根DOM节点上调用
.getElementsByTagName("parseerror"),如果返回的节点列表的长度大于零,就假设有错误吗? -
从技术上讲,我正在解析的 XML 文档可能包含
<parsererror>元素,但仍然是完全有效的 XML(元素将来自不同的命名空间)所以我必须多次调用.getElementsByTagNameNS(namespace, 'parsererror')来自每个浏览器的namespaceURI。 -
嗯。至少可以说,HTML5 规范是零碎的。
-
我注意到了这个mozilla bug,它指向了这个whatwg spec。我认为浏览器不使用异常是愚蠢的:正如您所写,我们可能不得不解析类似于作为错误返回的 XML 文档,并且无法判断它是否有效。完全解决问题的唯一方法是编写另一个解析器。
-
看起来 Chrome 的功能与 Safari 相同。
标签: javascript xml