在跨浏览器方式中使用Javascript的DOMParser时,如何检测XML解析错误? [英] How do I detect XML parsing errors when using Javascript's DOMParser in a cross-browser way?

查看:119
本文介绍了在跨浏览器方式中使用Javascript的DOMParser时,如何检测XML解析错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎所有主流浏览器都实现了DOMParser API,以便可以将XML解析为DOM,然后使用XPath,getElementsByTagName等进行查询...

It seems that all major browsers implement the DOMParser API so that XML can be parsed into a DOM and then queried using XPath, getElementsByTagName, etc...

但是,检测解析错误似乎更棘手。 DOMParser.prototype.parseFromString 始终返回有效的DOM。发生解析错误时,返回的DOM包含< parsererror> 元素,但在每个主要浏览器中略有不同。

However, detecting parsing errors seems to be trickier. DOMParser.prototype.parseFromString always returns a valid DOM. When a parsing error occurs, the returned DOM contains a <parsererror> element, but it's slightly different in each major browser.

示例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));

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>&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>

Safari中的结果:

< root> 元素正确分析,但包含一个嵌套的< parsererror> 名称空间比Opera和Firefox的< parsererror> 元素。

The <root> element parses correctly but contains a nested <parsererror> in a different namespace than Opera and Firefox's <parsererror> element.

<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吗?

推荐答案

这是我提出的最佳解决方案。

This is the best solution I've come up with.

我试图解析故意无效的XML字符串并观察生成的< parsererror> 元素的命名空间。然后,在解析实际的XML时,我可以使用 getElementsByTagNameNS 来检测相同类型的< parsererror> 元素并抛出一个Javascript 错误

I attempt to parse a string that is intentionally invalid XML and observe the namespace of the resulting <parsererror> element. Then, when parsing actual XML, I can use getElementsByTagNameNS to detect the same kind of <parsererror> element and throw a Javascript Error.

// My function that parses a string into an XML DOM, throwing an Error if XML parsing fails
function parseXml(xmlString) {
    var parser = new DOMParser();
    // attempt to parse the passed-in xml
    var dom = parser.parseFromString(xmlString, 'text/xml');
    if(isParseError(dom)) {
        throw new Error('Error parsing XML');
    }
    return dom;
}

function isParseError(parsedDocument) {
    // parser and parsererrorNS could be cached on startup for efficiency
    var parser = new DOMParser(),
        errorneousParse = parser.parseFromString('<', 'text/xml'),
        parsererrorNS = errorneousParse.getElementsByTagName("parsererror")[0].namespaceURI;

    if (parsererrorNS === 'http://www.w3.org/1999/xhtml') {
        // In PhantomJS the parseerror element doesn't seem to have a special namespace, so we are just guessing here :(
        return parsedDocument.getElementsByTagName("parsererror").length > 0;
    }

    return parsedDocument.getElementsByTagNameNS(parsererrorNS, 'parsererror').length > 0;
};

请注意,这个解决方案没有'包括Internet Explorer所需的特殊外壳。但是,IE中的内容要简单得多。使用 loadXML 方法解析XML,如果解析成功则返回true或false分别失败。请参阅 http://www.w3schools.com/xml/xml_parser.asp举个例子。

Note that this solution doesn't include the special-casing needed for Internet Explorer. However, things are much more straightforward in IE. XML is parsed with a loadXML method which returns true or false if parsing succeeded or failed, respectively. See http://www.w3schools.com/xml/xml_parser.asp for an example.

这篇关于在跨浏览器方式中使用Javascript的DOMParser时,如何检测XML解析错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆