Ajax Course

Parsing XML document
Complete example of parsing and displaying XML data

XML (Extensible Markup Language) is a special format for structuring and storing data in files with .xml extension, with a syntax based on tags. In some cases, the response received by Ajax (data transmitted from the server script) can be an XML document content. This method is commonly used in API applications when datas are transferred from one server to another (from an external server to the site that has requested the transfer).
This tutorial shows you how to get data from an XML file and display it in the web page, using Ajax.

Loading XML Data

The first step is getting data from XML. This data may be received from PHP (or other server application) as a string with XML format, or can be downloaded directly from an XML file.
After the XML data were received, it must be loaded (stored) in a JavaScript DOM object.

  1) If the XML content is received in a single string, from a server side script, the JavaScript code to load that XML format in a JS DOM object is the fallowing (explanations are in the script code):
// loads the xml string in a dom object
function getXML_sir(txt_xml) {
 // https://coursesweb.net/ajax/
  // for non IE browsers
  if(window.DOMParser) {
    // create an instance for xml dom object
    getxml = new DOMParser();
    xmlDoc = getxml.parseFromString(txt_xml,"text/xml");
  }
  else {
    // for Internet Explorer
    // create an instance for xml dom object
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
  }
  return xmlDoc;
}

// a variable with the string received from server
var str_xml = 'The string that contains the XML content received from the server by ajax';

// calls the getXML_sir() with "str_xml" function and store the xml dom in a variable
var xml_dom = getXML_sir(str_xml); 
- Internet Explorer uses the "ActiveXObject("Microsoft.XMLDOM")" to load XML data into a DOM object, other browsers use the "DOMParser()" function and "parseFromString(string_XML, 'text/xml')" method.
- The variable "str_xml" shall contain a string with XML content, received by Ajax from a PHP script.

2) If the XML data must be downloaded directly from an XML file, use the XMLHttpRequest object.
// Ajax function, gets the content of an xml file and stores it in XML DOM
function getXML_file(xml_file) {
 // https://coursesweb.net/ajax/
  var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');  // XMLHttpRequest object

  // sets and sends the request for calling "xml_file"
  xhttp.open("GET", xml_file ,false);
  xhttp.send(null);

  // sets and returns the content as XML DOM
  xmlDoc = xhttp.responseXML;

  return xmlDoc;
}

// XML file address
var file_xml = 'xml_file.xml';

// calls the "getXML_file()" function "file_xml"
var xml_dom = getXML_file(file_xml); 
- the "responseXML" transforms the XML content directly in XML DOM.

Parsing XML document

Once the XML content was transformed into JavaScript XML DOM, you can access any XML element by using JS DOM methods.
Since XML data is structured in a format based on tags, you can use JavaScript DOM properties and specific methods for parsing them. Here are some of the most used.

Some JavaScript DOM Properties

Some JavaScript DOM Methods


• Now will be presented some examples with these properties and methods.
For these examples will be used the following XML document, named "file.xml":
<?xml version="1.0" encoding="utf-8"?>
<webcourses>
  <site categ="Web Programming">
    <url>https://coursesweb.net/php-mysql/</url>
    <description>Free PHP-MySQL online course and tutorials</description>
  </site>
  <site categ="Web Programming">
    <url>https://coursesweb.net/ajax/</url>
    <description>Free Ajax course and tutorials</description>
  </site>
  <site categ="Foreign languages">
    <url>https://marplo.net/engleza</url>
    <description>Free online English lessons</description>
  </site>
</webcourses>
After you get with Ajax the XML data and convert it into XML DOM object (with one of the functions above: "getXML_sir()" if it's a text string, or "getXML_file" if it's taken directly from external file), this object is stored in a variable, here named "xml_dom". This variable becomes the basis for the implementation of DOM properties and methods.

1. Example with firstChild and nodeName
<script type="text/javascript"><!--
// Add the function "getXML_file()" or "getXML_sir()" (depending on the mode of XML data acquisition)
// Here it's used "getXML_file()"

var xml_dom = getXML_file('fisier.xml');         // calls the "getXML_file()" function with the name of the XML file

var root = xml_dom.firstChild;         // gets the first child element, the root tag
var tag_root = root.nodeName;         // gets the name of root tag

alert(tag_root);         // webcourses
//--></script>

2. Example with getElementsByTagName and getAttribute()
<script type="text/javascript"><!--
// Add the function "getXML_file()" or "getXML_sir()" (depending on the mode of XML data acquisition)
// Here it's used "getXML_file()"

var xml_dom = getXML_file('fisier.xml');         // calls the "getXML_file()" function with the name of the XML file

var arr_sites = xml_dom.getElementsByTagName('site');         // gets an Array with all "site" tags
var site2_cat = arr_sites[1].getAttribute('categ');         // gets the value of "categ" attribute of second "site" tag

alert(site2_cat);         // Web Programming
//--></script>

3. Example with childNodes and nodeValue
<script type="text/javascript"><!--
// Add the function "getXML_file()" or "getXML_sir()" (depending on the mode of XML data acquisition)
// Here it's used "getXML_file()"

var xml_dom = getXML_file('fisier.xml');         // calls the "getXML_file()" function with the name of the XML file

var site2 = xml_dom.getElementsByTagName('site')[1];         // gets the second "site" element
var site2_tag1 = site2.getElementsByTagName('url')[0];         // gets the first 'url' tag of "site2" node

// gets the value of first child node of site2_tag1 node
var site2_tag1v = site2_tag1.childNodes[0].nodeValue;

alert(site2_tag1v);         // Displays: "https://marplo.net/ajax"
//--></script> 

Complete example of parsing and displaying XML data

The following example uses the same XML document, from "file.xml", its data will be parsed and displayed in an HTML table.
<div id="ajax_xml">This is the area where the table with XML data retrieved by Ajax will be displayed</div>
<script type="text/javascript"><!--
// Ajax function, gets the content of an xml file and stores it in XML DOM
function getXML_file(xml_file) {
 // https://coursesweb.net/
  var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');  // XMLHttpRequest object

  // sets and sends the request for calling "xml_file"
  xhttp.open("GET", xml_file ,false);
  xhttp.send(null);

  // sets and returns the content as XML DOM
  xmlDoc = xhttp.responseXML;

  return xmlDoc;
}

// this function return
function htmlTab_xml(file_xml) {
  // this variable stores the code of the html table
  var html_tab = '<table id="id_tabel" align="center" width="99%"><tr><th>Category</th><th>URL</th><th>Description</th></tr>';

  var xml_dom = getXML_file(file_xml);           // calls the "getXML_file()" function with the name of the XML file

  var arr_sites = xml_dom.getElementsByTagName('site');         // gets an Array with all "site" tags

  // traverses the "arr_sites" array
  for(var i=0; i<arr_sites.length; i++) {
    var site_cat = arr_sites[i].getAttribute('categ');         // gets the value of 'categ' element of current "site" tag

    // gets the value of first child-node of first 'url' element of current "site" tag
    var site_url = arr_sites[i].getElementsByTagName('url')[0].childNodes[0].nodeValue;

    // gets the value of first child-node of first 'description' element of current "site" tag
    var site_desc = arr_sites[i].getElementsByTagName('description')[0].childNodes[0].nodeValue;

    // adds the values in the html table
    html_tab += '<tr><td>'+ site_cat+ '</td><td>'+ site_url+ '</td><td>'+ site_desc+ '</td></tr>';
  }

  html_tab += '</table>';           // close the code for html tabel

  return html_tab;          // returns the table
}

var file_xml = 'file.xml';          // the name of the XML file

// adds the html table in a html tag, with id="ajax_xml"
document.getElementById('ajax_xml').innerHTML = htmlTab_xml(file_xml); 
--></script>
- To see the result of this Ajax - XML example, click on the:
This is the area where the table with XML data retrieved by Ajax will be displayed

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
}
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
alert(content);
Click on the "echo" correct instruction.
echo "CoursesWeb.net" echo "CoursesWeb.net"; echo ""CoursesWeb.net";
echo "Address URL: http://CoursesWeb.net";
AJAX and XML

Last accessed pages

  1. PHP Unzipper - Extract Zip, Rar Archives (31748)
  2. Node.js Course (2599)
  3. Date and Time in ActionScript 3 (9973)
  4. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (55419)
  5. Execute JavaScript scripts loaded via AJAX (7844)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (295)
  2. Read Excel file data in PHP - PhpExcelReader (101)
  3. The Four Agreements (89)
  4. PHP Unzipper - Extract Zip, Rar Archives (87)
  5. The Mastery of Love (83)
Chat
Chat or leave a message for the other users
Full screenInchide