小编csp*_*ode的帖子

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

似乎所有主流浏览器都实现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, 'text/xml');
console.log((new XMLSerializer()).serializeToString(dom));
Run Code Online (Sandbox Code Playgroud)

Opera中的结果:

DOM的根是一个<parsererror>元素.

<?xml version="1.0"?><parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">Error<sourcetext>Unknown source</sourcetext></parsererror>
Run Code Online (Sandbox Code Playgroud)

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>&lt;root xmlns="http://default" xmlns:other="http://other"&gt;&lt;child&gt;&lt;otherr:grandchild/&gt;&lt;/child&gt;&lt;/root&gt;
---------------------------------------------------------------^</sourcetext></parsererror>
Run Code Online (Sandbox Code Playgroud)

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 …
Run Code Online (Sandbox Code Playgroud)

javascript xml

24
推荐指数
3
解决办法
2万
查看次数

标签 统计

javascript ×1

xml ×1