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.
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.
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 ="";
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
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
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
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
$( 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