在跨浏览器方式中,使用Javascript的DOMParser时,如何检测XML解析错误?

10 浏览
0 Comments

在跨浏览器方式中,使用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的根是一个元素。

ErrorUnknown source

在Firefox中的结果:

DOM的根是一个元素。

XML Parsing Error: prefix not bound to a namespace

Location: http://fiddle.jshell.net/_display/

Line Number 1, Column 64:<root xmlns="http://default" xmlns:other="http://other"><child><otherr:grandchild/></child></root>

---------------------------------------------------------------^

在Safari中的结果:

元素正确解析,但包含一个嵌套在Opera和Firefox的元素中的不同命名空间的

This page contains the following errors:

error on line 1 at column 50: Namespace prefix otherr on grandchild is not defined

Below is a rendering of the page up to the first error.

我是否错过了一种简单的跨浏览器的方法来检测XML文档中是否发生了解析错误?还是必须查询每个可能生成的元素的DOM?

0