user2711066 user2711066 - 1 month ago 30
Javascript Question

How to read xml file using javascript in chrome Only

I had facing to read XML file using java script in chrome browser.My code will work fine in Firefox, IE and even opera browser also.Yet Chrome browser will not support to read XML file.

Here my customize code:

function loadXMLDoc(dname) {
try //Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
} catch (e) {
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc = document.implementation.createDocument("", "", null);
} catch (e) {
alert(e.message)
}
}
try {
xmlDoc.async = false;
xmlDoc.load(dname);
return (xmlDoc);
} catch (e) {
alert(e.message)
}
return (null);
}

function loadXMLString(txt) {
try //Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(txt);
return (xmlDoc);
} catch (e) {
try //Firefox, Mozilla, Opera, etc.
{
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
return (xmlDoc);
} catch (e) {
alert(e.message)
}
}
return (null);
}

function loadXMLDocFromString(txt) {
try //Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(txt);
return (xmlDoc);
} catch (e) {
try //Firefox, Mozilla, Opera, etc.
{
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
return (xmlDoc);
} catch (e) {
alert(e.message)
}
}
return (null);
}


Here, above code will get from this W3school tutorial How to solve it only chrome browser.When i execute that function can't held in chrome and it results like


Object# has no method "load".


how to read XML file in chrome browser using java script. please guide me

Answer

Use XMLHttpRequest instead of document.implementation.createDocument XMLHttpRequest is done for that, and as you can see in this grid :

http://www.steveborn.com/codenotes/LoadingXML.htm

document.implementation.createDocument doesn't work on Chrome and Safari.

You should redefine your loadXMLDoc like this to be cross-browser compatible :

function loadXMLDoc (dname) {
    var xmlDoc;

    try {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open('GET', dname, false);
        xmlhttp.setRequestHeader('Content-Type', 'text/xml');
        xmlhttp.send('');
        xmlDoc = xmlhttp.responseXML;
    } catch (e) {
        try {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        } catch (e) {
            console.error(e.message);
        }
    }
    return xmlDoc;
}