Introduction
Often, we call web services that return data either in XML or JSON format. For JSON, we can easily get the data using JavaScript. But, what to do if we get it in XML format?
Well, we will discuss how to get data from XML using JavaScript and jQuery, in this blog.
Using Code
We will use the following XML data in our example.
- <?xml version="1.0" encoding="utf-8"?>
- <Events>
- <EventItem id="101">
- <Country>India</Country>
- <Phone Link="12345">Home</Phone>
- </EventItem>
- <EventItem id="102">
- <Country>USA</Country>
- <Phone Link="123">LandLine</Phone>
- </EventItem>
- </Events>
Using JavaScript
First, it checks for the availability of window.ActiveXObject object. This object is basically used for Internet Explorer (IE) browser. If it is IE, then it has different method (loadXML()) to parse the XML data. If it is non-IE, it creates DOM parser and calls the parseFromString() method for parsing the XML data.
Here is the code:
- var strXML = '<?xml version="1.0" encoding="utf-8"?><Events><EventItem id="101"><Country>India</Country><Phone Link="12345">homes</Phone></EventItem></Events>';
-
- var doc;
- if(window.ActiveXObject)
- {
- doc = new ActiveXObject('Microsoft.XMLDOM');
- doc.async = 'false';
- doc.loadXML(strXML);
- }
- else
- {
- var parser = new DOMParser();
- doc = parser.parseFromString(strXML, 'text/xml');
- }
-
- var x = doc.getElementsByTagName("EventItem");
- for (i = 0;i < x.length; i++)
- {
- alert(x[i].getElementsByTagName("Country")[0].childNodes[0].nodeValue);
- alert(x[i].getElementsByTagName("Phone")[0].getAttribute('Link') );
- }
Using jQuery
In jQuery, it uses parseXML() method to create a valid XML Document from a string. We can use find() method to get the data based on the node name. Additionally, if we have multiple node blocks, then it loops over to get the data for each node. In our example, we have multiple events. So, $.each() is required to get all the records.
If you want to use attribute value, then you can use attr(). Follow the below code:
- <script type="text/javascript">
- var strXML = '<?xml version="1.0" encoding="utf-8"?><Events><EventItem id="101"><Country>India</Country><Phone Link="12345">homes</Phone></EventItem></Events>';
-
- var doc = $.parseXML(strXML);
- $eventItem = $(doc).find("EventItem");
-
- $eventItem.each(function(index, element) {
- alert("ID: " + element.attributes["id"].value);
- alert("Country: " + $(element).find('Country').text());
- alert("Phone: " + $(this).children('Phone').attr('Link'));
- });
-
- $(doc).find('EventItem').each(function () {
- var id, cName, phoneNo;
-
- id = $(this).attr('id');
- cName = $(this).children('Country').text();
- phoneNo = $(this).children('Phone').attr('Link');
-
- alert($(this).children('Phone[Link="12345"]').text());
- });
-
- </script>
Conclusion
In this article, we discussed how to get data from XML. Hope this helps you.