Loading local XML file in Chrome

2019-05-07 20:27发布

问题:

I have to make a project for work using HTML5/CSS3/JavaScript, and using XML as the dataprovider. The requirements state that it has to be compatible with Internet Explorer, Firefox, Safari and Chrome. I'm developing in Firefox, so that works just fine. Safari works like a treat as well, and luckily it works perfect in the new IE9.

I'm only having problems getting it to run in Chrome. As Chrome seems to support a lot of the new HTML5/CSS3 features, it shouldn't be too much work to get it running in that browser as well. The only problem is that it refuses to load the XML file, and since this is required from the get-go, the entire thing won't load.

After doing some research, I came across posts stating that Chrome does not allow you to load local XML files. It should work offline without using Apache or anything, so is there any way to still get it working?

The snippet of code where I load my XML depending on the browser being used:

if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
    // INTERNET EXPLORER
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        try {
            xmlDoc.async="true";
            xmlDoc.load("exercise1.xml");
        } catch(ex) {
            alert("exception");
            alert(ex.message);
        }
    }else if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
    // MOZILLA FIREFOX
        // load xml file
        xmlDoc=loadXMLDoc("exercise1.xml");
    }else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
        // GOOGLE CHROME
        // load xml file
        // ????????
    }else if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
        // OPERA
        alert("Opera is not supported as of now");
    }else if (browser.toLowerCase().indexOf('safari') > 0){
    // APPLE SAFARI
        // load xml file
        xmlDoc=loadXMLDoc("exercise1.xml");
    } else {
    // OTHER BROWSERS
        // load xml file
        xmlDoc=loadXMLDoc("exercise1.xml");
    }

Firefox and Safari use an external JavaScript to load the XML. I don't think it's really necessary to post that code here, since it works perfectly fine in those browsers.

Perhaps I've overlooked something simple, but I've done a fair bit of googling and tried some code found here on Stackoverflow, and I still can't get it to work..

回答1:

You can load an XML file in Chrome using XMLHttpRequest like this: (tested on Chrome 12.0.742.112).

    function readxml()
    {
        xmlHttp = new window.XMLHttpRequest();
        xmlHttp.open("GET","test.xml",false);
        xmlHttp.send(null);
        xmlDoc = xmlHttp.responseXML.documentElement;
    }

This is the resulting xmlDoc seen in Chrome development tools.

Be sure to have a valid XML document on the server.

<?xml version='1.0'?>

must be on first line of XML and also check that there are no spaces before the tag.