How to parse XML file in WRT widget using JQuery
Article Metadata
Contents |
Introduction
To parse a remote or a local XML file for your widget, e.g. to display it on-screen, you could use jQuery JavaScript library as solution, for both AJAX call and parsing.
Prerequisites
- jquery.js must exist in the project folder and be included
Example code
We will use first an AJAX call to get the XML document. If the call was successful, the function XML_parsing_sequence will be called. In the call we will also define data type to be "xml". This will ensure that the passed parameter is in a correct form for parsing.
Functions "each" & "find" will be used in going through the document. First, the "each" is looping the tags with the given name and then "find" will be looking for a specific tag.
Notes:
- If you would like to search using also by an attribute, you should add them to the XML document. See the comment in code.
- There are more tags in the XML file in this example, so you could easily try to change the code to find something else, or all of them if you like.
basic.js - code for WRT default JavaScript file
function XML_parsing_sequence(xml)
{
$(xml).find("food").each(function()
{
$("#output").append($(this).find("name").text());
//Use the line below, if you have added an attribute to the XML file, e.g. <food id="1">
//$("#output").append($(this).attr("id")+"<br />");
//Add just one extra line in between each tag to form a list
$("#output").append("<br>");
});
}
index.html - code for WRT default HTML-file
...
<script language="javascript" type="text/javascript" src="jquery.js"></script>
...
<body onLoad="javascript:init();">
<div id="output" align="center" ></div>
</body>
...
The purpose for the "output" div is to display the results of the parsing, received from the basic.js.
XML file for testing
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>
two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>
light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>
light Belgian waffles covered with an assortment of fresh berries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>
thick slices made from our homemade sourdough bread
</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>
two eggs, bacon or sausage, toast, and our ever-popular hash browns
</description>
<calories>950</calories>
</food>
</breakfast_menu>


(no comments yet)