PDA

View Full Version : Searching a DOM tree.


nkline
02-15-2008, 05:22 PM
Greetings,

I'm in the process of learning how JavaScript can be used to work with the DOM.
I have a specific problem I'm trying to solve but unfortunately my skills aren't
advanced enough at this point to know how to quickly solve the problem at hand.

Here is an excerpt of the XML file I am working with:

<item>
<title>Recipe of the Week: 5-Minute Ginger Pineapple</title>
<link>http://whfoods.org/genpage.php?tname=recipe&amp;dbid=236</link>
<description>Recipe of the Week: 5-Minute Ginger Pineapple</description>
<pubDate>Mon, 11 Feb 2008 08:14:45 -0600</pubDate>
<guid isPermaLink="false">tag:whfoods.org,2008-02-11:whfoods.tname=recipe&amp;dbid=236</guid>
</item>

In this XML file are an infinite number of <item> nodes, each containing different information.

First, I want to search the XML file for the string "Recipe of the Week", which will be located in a <title> node.
Second, I then want to grab the <title> node's parent node, which is <item>, and all of its children and their information.
All of this information will then be stored in a variable so that I can then access the information I need.
For example, I could then locate and do what I want with the <title>, <link>, <description>, etc. nodes.

Unfortunately, I have found little information on how to search an XML file for a specific string.
I'm familiar with regular expressions, but I have a feeling there are more efficient ways of searching
an XML file in this case.

I would appreciate your thoughts and recommendations on the correct way to solve this problem.
Also, I would greatly appreciate recommendations on some quality JavaScript/DOM materials, including book recommendations.

Thank you for your time,

*Nick*

Ultragames
02-16-2008, 10:57 PM
Well first of all, do you have a way yet that you are getting the XML file into Javascript to parse it at all? If not, try AJAX. This should give you a place to start:

// Use AJAX, and set your responce to the variable named req
var items = req.responseXML.getElementsByTagName('item').item(0);

if( items.length >= 1 ){
for( var x = 0; x < items.length; x++ ){
if( items[x].firstChild.nodeName.toLowerCase() == 'title' && items[x].firstChild.nodeValue.indexOf('Recipe of the Week:')>=0 ){
// Do something with items[x]
}
}
}

And some light reading (http://www.howtocreate.co.uk/tutorials/javascript/domintroduction) as well.