Example #1:
Using getElementsByTagName, we iterate thru the XML tree and read the numerous children/sibling.
<html> <body> <script> var xmlstring = '<?xml version=\"1.0\"?>\ <shoppingcart date="14-10-2005" total="123.45">\ <item code="12345">\ <name>Widget</name>\ <quantity>1</quantity>\ </item>\ <item code="54321">\ <name>Another Widget</name>\ <quantity>2</quantity>\ </item>\ </shoppingcart>'; // convert the string to an XML object var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml"); // get the XML root item var root = xmlobject.getElementsByTagName('shoppingcart')[0]; var date = root.getAttribute("date"); alert("shoppingcart date=" + date); var items = root.getElementsByTagName("item"); for (var i = 0 ; i < items.length ; i++) { // get one item after another var item = items[i]; // now we have the item object, time to get the contents // get the name of the item var name = item.getElementsByTagName("name")[0].firstChild.nodeValue; // get the quantity var quantity = item.getElementsByTagName("quantity")[0].firstChild.nodeValue; alert("item #" + i + ": name=" + name + " quantity=" + quantity); } </script> </body> </html>
Example #2:
Here is a more universal example with the method "childNodes".<html> <body> <script> var xmlstring = '<?xml version="1.0"?>\ <root>\ <data>\ <row>\ <cell>Admiral</cell>\ <cell>Melon</cell>\ <cell>Carrot</cell>\ </row>\ <row>\ <cell>Captain</cell>\ <cell>Banana</cell>\ <cell>Zucchini</cell>\ </row>\ </data>\ <data>\ <row>\ <cell>Midshipman</cell>\ <cell>Orange</cell>\ <cell>Potatoe</cell>\ </row>\ </data>\ </root>'; // convert the string to an XML object var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml"); // get the XML root item var root = xmlobject.getElementsByTagName('root')[0]; for (var iNode = 0; iNode < root.childNodes.length; iNode++) { var node = root.childNodes.item(iNode); for (i = 0; i < node.childNodes.length; i++) { var sibling = node.childNodes.item(i); for (x = 0; x < sibling.childNodes.length; x++) { var sibling2 = sibling.childNodes.item(x); if (sibling2.childNodes.length > 0) { var sibling3 = sibling2.childNodes.item(0); alert(sibling3.data); } } } } </script> </body> </html>