所有主要浏览器似乎都实现了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>
元素解析正确,但包含一个不同命名空间下的嵌套<parsererror>
,而Opera和Firefox的<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吗?
.getElementsByTagName("parseerror")
,并假设如果返回的节点列表长度大于零,则存在错误吗? - Pointy