Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read XML file using JavaScript in Chrome

I need to load and read an XML file using JavaScript.

The following code works fine in Firefox, IE and Opera:

function loadXMLDoc(dname) {
  var xmlDoc

  // Internet Explorer
  try {
    xmlDoc = new ActiveXObject('Microsoft.XMLDOM')
  }
  catch (e) {
    // Firefox, Opera, etc.
    try {
      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
}

But executing this code in Chrome gives me this error:

Object# has no method "load"

like image 839
user2711066 Avatar asked Aug 26 '13 10:08

user2711066


People also ask

How do I view XML files in Chrome?

View an XML file in a browser In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome". When you do, the file will open in a new tab.

Can JavaScript read XML?

Several key methods and properties in JavaScript can help in getting information from an XML file. In the section, a very simple XML file is used to demonstrate pulling data from XML into an HTML page using JavaScript to parse (interpret) the XML file.

Can browsers parse XML?

All modern browsers have a built-in XML parser that can convert text into an XML DOM object.

How do I open an XML readable file?

XML files can be opened in a browser like IE or Chrome, with any text editor like Notepad or MS-Word. Even Excel can be used to open XML files. We also have Online editors to open XML files.


1 Answers

Legacy Code

document.implementation.createDocument does not work on Chrome and Safari.

Use XMLHttpRequest instead when possible:

function loadXMLSync(url) {
  try {
    // Prefer XMLHttpRequest when available
    var xhr = new XMLHttpRequest()
    xhr.open('GET', url, false)
    xhr.setRequestHeader('Content-Type', 'text/xml')
    xhr.send()

    return xhr.responseXML
  }
  catch (e) {
    // XMLHttpRequest not available, fallback on ActiveXObject
    try {
      var activex = new ActiveXObject('Microsoft.XMLDOM')
      activex.async = false
      activex.load(url)

      return activex
    }
    catch (e) {
      // Neither XMLHttpRequest or ActiveXObject are available
      return undefined
    }
  }
}

Modern Browsers

If you're targeting modern browsers (> IE6), just use XMLHttpRequest:

function loadXMLSync(url) {
  var xhr = new XMLHttpRequest()

  xhr.open('GET', url, false)
  xhr.setRequestHeader('Content-Type', 'text/xml')
  xhr.send()

  return xhr.responseXML
}
like image 193
kube Avatar answered Oct 16 '22 14:10

kube