ParseFromString throws error in IE, but not in Chrome

半城伤御伤魂 提交于 2019-12-05 17:19:15

When the XML is malformed non-Microsoft browsers (Firefox, Chrome, etc) it will create the XML document with the error message as it's content. Click here (<-- click there).

When the XML is malformed in Microsoft browsers, IE and Edge, it throws an error, writes an error to the console and your script stops. Note I'm on a Mac so I've tested this remotely but have not had a chance to test it personally. You can put that code in a try catch block for IE but what I mean is I don't know if that will stop it from writing a message to the console.

Here's the code pen with intentionally malformed XML and the error message is written in the output. There is no error in the codepen or output. I'm intentionally writing the error code from the parser to the output window. Open the console to see what's going on.

FWIW IE is the correct behavior IMHO. Not throwing errors was the Internet way to do things until relatively recently. The problem with not throwing errors is you don't know what you did wrong or where. Write once, debug everything.

Also, until more recent versions, IE used ActiveX to parse XML documents.

From W3C XML validation script:

function validateXML(text) {
    var message;
    var parser;
    var xmlDoc;

    // code for Edge, IE, Mozilla, Firefox, Opera, etc.
    if (document.implementation.createDocument || window.DOMParser) {
        parser = new DOMParser();

        try {
            xmlDoc = parser.parseFromString(text, "text/xml");
        }
        catch (error) {

        }

        if (xmlDoc.getElementsByTagName("parsererror").length > 0) {
            return xmlDoc.getElementsByTagName("parsererror")[0];
        }
        else {
            return "No errors found";
        }
    }
    // code for older versions of IE
    else if (window.ActiveXObject) {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";

        try {
            xmlDoc.loadXML(text);
        }
        catch (error) {

        }

        if (xmlDoc.parseError.errorCode != 0) {
            message = "Error Code: " + xmlDoc.parseError.errorCode + "\\n";
            message = message + "Error Reason: " + xmlDoc.parseError.reason;
            message = message + "Error Line: " + xmlDoc.parseError.line;
            return message;
        }
        else {
            return "No errors found";
        }
    }

    else {
        return "Not supported";
    }
}

Related question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!