HomeGuidesSnippets

Loading XML data

July 26, 2021

post-bg

I will almost always take JSON over XML - and by almost I mean always - but recently I had to load an external > XML file for the very first time.

How to load an external XML file

Both the XMLHttpRequest Object API and the Fetch API allow for data transfer between a web-browser and a web server. Main difference being that fetch uses Promises.

XMLHttpRequest

  • Create a new XMLHttpRequest object (xhr)
  • Use open to set URL and HTTP method (in this case GET)
  • Set the request header
  • Define an event listener
  • Send the request and the response will be the XML file

Function to load XML

It takes 2 parameters: the URL of the XML data and a callback function, that is going to be called once the XML file is loaded.

let getXMLFile = function(url, callback) {
  let request = new XMLHttpRequest();
  request.open('GET', url);

  //set header
  request.setRequestHeader(
    'Content-Type', 'text/xml'
  );

  request.onreadystatechange = function() {
    if (
      request.readyState === 4
      && request.status === 200
    ) {
      callback(request.responseXML);
    }
  }
  request.send();
};

Loading XML Data with Fetch

let getXMLFile = function(url,callback) {
  fetch(url)
    .then(resp => {
      return resp.text();
    })
  .then((data) => {
    let parser = new DOMParser(),
    xmlDoc = parser.parseFromString(
      data, 'text/xml'
  );
  callback(xmlDoc);
  })
}

Calling above function

If you open the dev console, you may see an error: Cross origin request ... The XML API relies in the HTTP protocol, and if you're opening the file straight in the browser, it's not going to have access to it. What you have to do then is place the file on a server or run it with a local server using something like Gulp, Grunt, Node or MAMP etc.

//sample Url
const url: 'https://archive.org/items/files.xml';

//function with callback param
getXMLFile(url, function(xml) {
  console.log(xml)
})

How to work with XML data

The data you get back is of type string, and it needs to be converted to XML Dom; which is done using the DOM parser.

let parser = new DOMParser(),
  xmlDoc = parser.parseFromString(
    xml, 'text/xml
  );

Manipulate data with tags

Using the xmlDoc created above with DOM methods

//To get all files:
>$ xmlDoc.getElementsByTagName('files')[0];

//To get first file:
>$ xmlDoc.getElementsByTagName('files')[0]
   .firstChild;

//To get first file text value:
$ > xmlDoc.getElementsByTagName('files')[0]
    .firstChild.nodeValue;

Sample Xml response/ data

<files>
  <file name="39Steps.js" source="original">
  <format>ASR</format>
  <mtime>1541138665</mtime>
  <size>4839</size>
  <md5>bca99229748c30bcb86e18</md5>
  <crc32>52262c22</crc32>
  <sha1>221aa518c77efa66026b5f</sha1>
  </file>
</files>
  • Terms & Conditions
  • kcosa.com © 2022
  • Privacy Policy