selectSingleNode works but not selectNodes
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
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.
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);
}
As the method name suggests, selectNodes
returns a collection (array). You need to loop over them. Or if you're sure of the structure, grab the first element.
精彩评论