views:

55

answers:

3

Javascript:

var req=xmlDoc.responseXML.selectSingleNode("//title");
alert(req.text);

as expected, returns the text of the first "title" node.

but this

var req=xmlDoc.responseXML.selectNodes("//title");
alert(req.text);

returns "undefined." The following:

var req=xmlDoc.responseXML.selectNodes("//title").length;
alert(req);

returns "2." I don't get it. Maybe when I selectNodes it isn't getting the text node inside the title. That's my guess for now...here is the xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd">
<catalog>
<decal>
<company>Victor</company>
<title>Wood Horn Blue Background</title>
<image>
<url>victor01.jpg</url>
<width>60</width>
<height>60</height>
<name>Wood Horn Blue Background</name>
<link></link>
</image>
<price>$15.00</price>
<instock>In Stock</instock>
<notes>no extra info</notes>
</decal>
<decal>
<company>Victor</company>
<title>Wood Horn without Black Ring</title>
<image>
<url>victor02.jpg</url>
<width>60</width>
<height>60</height>
<name>Wood Horn Without Black Ring</name>
<link></link>
</image>
<price>$15.00</price>
<instock>In Stock</instock>
<notes>no extra info</notes>
</decal>
</catalog>

thanks

+3  A: 

selectNodes returns an array.

Therefore, when you write var req=xmlDoc.responseXML.selectNodes("//title"), the req variable holds an array of elements.
Since arrays do not have a text property, you're getting undefined.

Instead, you can writereq[0].text to get the text of the first element in the array.

SLaks
can you elaborate a little bit please? I am new to this...
Troy
I just​​​​ did.
SLaks
sorry it didn't refresh here that fast. I want a list of the text in each <title>.
Troy
+1  A: 

As the method name suggests, selecdtNodes returns a collection (array). You need to loop over them. Or if you're sure of the structure, grab the first element.

Evan Trimboli
+2  A: 

selectNodes returns an array rather than a single node (hence the plural naming of the method).

You can use an indexer to get the individual nodes:

var req=xmlDoc.responseXML.selectNodes("//title");
for (var i=0;i<req.length;i++) {
   alert(req[i].text);
}
Rob Levine
I am trying this...
Troy
okay it worked but I had to make it "i<req.length" Thanks everyone!
Troy
actually it worked without the length
Troy
My bad - for completeness it should have req.length. I must have miss-typed. I'll edit now.
Rob Levine