Javascript – Parse XML

I find a very good blog by Steve Born about parsing XML in Javascript. There are all together 3 different ways to parse XML but not all of them are mutually compatible with all browsers.

  • ActiveX
  • createDocument
  • xmlHttpRequest


For more details please refer to Steve’s post. Since ActiveX is a Microsoft product, i didn’t want to talk about it as it only works in Internet Explorer.

This post would only show the xmlHttpRequest approach because it probably works among all normal browsers including FireFox, Chrome, Safari and Opera. Here comes the code.

In the webroot, i have created a folder called parse-xml with the following index.html

    <title>Parsing XML in Javascript</title>
    <script type="text/javascript">
      var xmlpath = "http://localhost/parse-xml/data.xml"
      var xmlhttp = new XMLHttpRequest();"GET", xmlpath, false);
      xmlhttp.setRequestHeader('Content-Type', 'text/xml');
      xmlDoc = xmlhttp.responseXML;
      function readXML() {
        //The XML root node name 
        //The 1st attribute of the 1st child in the company node
        //The id attribute of the 2nd child in the company node
        //The 1st year node id
        //The text content of the 2nd child in company node
  <body onload="javascript:loadxml();">


Prepare the following data.xml

<?xml version="1.0" encoding="UTF-8"?>
  <turnover id="turnover01">
    <year id="2000">100,000</year>
    <year id="2001">140,000</year>
    <year id="2002">200,000</year>
  <employee id="employee01">John</employee>


Since different browsers treat the newline differently, it is better to remove all the newline characters.

<?xml version="1.0" encoding="UTF-8"?><company><turnover id="turnover01"><year id="2000">100,000</year><year id="2001">140,000</year><year id="2002">200,000</year></turnover><employee id="employee01">John</employee></company>


Open the http://localhost/parse-xml/index.html. there would be alert boxes showing the XML content.
Thanks again Steve.

Done =)


6 thoughts on “Javascript – Parse XML”

Leave a Reply to ykyuen Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.