Using Javascript to parse XML strings

Many web services provide data in XML format. Luckily all modern browsers have a built-in XML parser and tools to parse and select tags in XML documents. The XML parser converts an XML document into an XML DOM object - which can then be manipulated with JavaScript using the same vocabulary as HTML.

Some useful javascript methods and properties

Properties
  • childNodes - The childNodes property returns a NodeList of child nodes for the document.
  • nodeValue - The nodeValue property sets or returns the value of a node, depending on its type.
  • textContent - The textContent property sets or returns the textual content of a node and its descendants.
  • On setting, any child nodes are removed and replaced by a single Text node containing the string this property is set to.
Methods

    The methods querySelector and querySelectorAll allow to select elements by CSS 3 query. The querySelector returns only first element (in tree depth-first walking order), the querySelectorAll gets all of them.

    These mehods are limited to modern browsers (note: only added to IE in IE8)
  • querySelector - The querySelector method get the first element in the document with specific node
  • querySelectorAll - The querySelectorAll method gets all element in the document with specific node
  • parseFromString - The parseFromString method is useful if you have an XML formatted text and you need to convert it to an XML document. For Internet Explorer, use method loadXML
Ojbects
  • DOMParser - Provides methods to build XMLDocument objects from XML formatted strings or streams.
  • ActiveXObject - The ActiveXObject object is used to create instances of OLE Automation objects in Internet Explorer on Windows operating systems. You can use the methods and properties supported by Automation objects in JavaScript. ActiveXObject object is only supported by Internet Explorer.

Here we setup and parse a string into an XML Document. Note that Internet Explorer uses its own method to parse text.

var myOrders = 
"<?xml version='1.0' encoding='UTF-8'?>" +
"<Orders>" +
   "<Order>" +
      "<OrderHeader>" +
          "<OrderNo>12345</OrderNo>" +
      "</OrderHeader>" +
      "<OrderDetails>" +	  
		 "<OrderDetail>" +	  
		    "<Sku>ABC</Sku>" +
	        "<Qty>2</Qty>" +
		 "</OrderDetail>" +	  
		 "<OrderDetail>" +	  
		    "<Sku>DEF</Sku>" +
	        "<Qty>4</Qty>" +
		 "</OrderDetail>" +	  
	  "</OrderDetails>" +
   "</Order>" +
   "<Order>" +
      "<OrderHeader>" +
          "<OrderNo>12346</OrderNo>" +
      "</OrderHeader>" +
      "<OrderDetails>" +	  
		 "<OrderDetail>" +	  
		    "<Sku>HIJ</Sku>" +
	        "<Qty>1</Qty>" +
		 "</OrderDetail>" +	  
		 "<OrderDetail>" +	  
		    "<Sku>KLM</Sku>" +
	        "<Qty>2</Qty>" +
		 "</OrderDetail>" +	  
	  "</OrderDetails>" +
   "</Order>" +"</Orders>";

if (window.DOMParser)
{
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(myOrders,"text/xml");
}
else // Internet Explorer
{
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async=false;
  xmlDoc.loadXML(myOrders);
}

var myValue ="";



1. Get value of first order number

document.write("<br/>1. Get value of first order number<br/>");
var myValue = xmlDoc.getElementsByTagName("OrderNo")[0].childNodes[0].nodeValue;
document.write(myValue + "<br/><hr>");
Output: 12345


2. Get value of first sku number in first order

document.write("<br/>2. get value of first sku number in first order<br/>");
myValue = xmlDoc.getElementsByTagName("Sku")[0].childNodes[0].nodeValue;
document.write(myValue + "<br/><hr>");
Output:

ABC


3. list SKUs ordered

	document.write("<br/>3. List all SKUs ordered<br/>");
	myValue = xmlDoc.getElementsByTagName("Sku");

	// list all all SKUs ordered
	for(i = 0; i < myValue.length; i++){  	
		var node = myValue[i].firstChild.nodeValue;
		document.write(node + "<br>");
	}

Output:
ABC
DEF
HIJ
KLM




4. Get all Orders Numbers and SKU Ordered for each Order using querySelector and querySelectorAll

	document.write("<br/>4. Get all Orders Numbers and SKU Ordered for each Order<br/>");
	myOrders= xmlDoc.getElementsByTagName("Order");	
	// iterate through orders
	for(x = 0; x < myOrders.length; x++){  			
		var myOrder = myOrders[x].querySelector('OrderNo').textContent;
		document.write(myOrder + "<br/>");
	
	// iterate through SKUS in each order
		var mySkus = myOrders[x].querySelectorAll('OrderDetail > Sku');		
		for(y = 0; y < mySkus.length; y++){						
			document.write("-- SKU: " + mySkus[y].firstChild.nodeValue + "<br/>");
		}
	}
	document.write("<hr>");
Output:
12345
-- SKU: ABC
-- SKU: DEF
12346
-- SKU: HIJ
-- SKU: KLM


5. Using jQuery parseXML and .find

	$( document ).ready(function() {	   
		var xmlDoc = $.parseXML(myOrders);
		var $xml = $(xmlDoc);		
		var itemCount = $xml.find("OrderDetail").length;						
		var Sku  = $xml.find("Sku");		
		var Qty = $xml.find("Qty");			
		 for ( i=0; i < itemCount; i++) {         
			document.write(Qty[i].innerHTML + " " + Sku[i].innerHTML + "<br/>");
		}
	});
Output:
2 ABC
4 DEF
1 HIJ
2 KLM