Widget Walkthrough - Using loops
(Page 3 of 5 )
The Widget reference manual states that you should use a try catch loop to perform XPath functions, so you can add one to your getData() function. You will first need to obtain the XML document and place it in a variable using the parse method:
try {
doc = XMLDOM.parse(feeddata);
Next, you need to specify which elements in the XML file you want to match. This is the XPath element of your function:
titlelist = doc.evaluate( "rss/channel/item/title" );
datatextarea.data = "";
You now need to create an array to hold the headlines as separate DOMElement objects:
titles = new Array();
In this particular rss file, there are always 19 headlines, however, if you were using a different feed, you may not know the number of headlines in advance so it is a good idea to use a for loop that operates on the length of your array:
for (n = 0; n < titlelist.length; n++) {
The DOMNodeList returned by the XPath function has a built-in property of item() which can be used to specify which DOMElement in the list you are referring to. In this case, we can match the number of the array item with the item we want to store in the array:
titles[n] = titlelist.item(n);
Finally, each time the loop iterates, you can set the data property of the <textarea> to the data held in the array item. The actual item held in the array is the DOMElement; to get the actual text held in the object you need to address the firstChild of the element. The JavaScript new line character is also specified (twice) to break up the headlines:
datatextarea.data += titles[n].firstChild.data + "nn";
}
}
catch(e) {
print(e);
}
Next: Fine tuning headline retrieval >>
More XML Articles
More By Dan Wellman