在跨浏览器方式中,使用Javascript的DOMParser时,如何检测XML解析错误?
在跨浏览器方式中,使用Javascript的DOMParser时,如何检测XML解析错误?
似乎所有主要的浏览器都实现了DOMParser API,以便将XML解析为DOM,然后可以使用XPath、getElementsByTagName等进行查询。
然而,检测解析错误似乎更加棘手。DOMParser.prototype.parseFromString始终返回一个有效的DOM。当发生解析错误时,返回的DOM包含一个
示例JavaScript:
xmlText = '
parser = new DOMParser();
dom = parser.parseFromString(xmlText, 'application/xml');
console.log((new XMLSerializer()).serializeToString(dom));
在Opera中的结果:
DOM的根是一个
在Firefox中的结果:
DOM的根是一个
Location: http://fiddle.jshell.net/_display/
Line Number 1, Column 64:
---------------------------------------------------------------^
在Safari中的结果:
error on line 1 at column 50: Namespace prefix otherr on grandchild is not definedThis page contains the following errors:
Below is a rendering of the page up to the first error.
我是否错过了一种简单的跨浏览器的方法来检测XML文档中是否发生了解析错误?还是必须查询每个可能生成的