2

Javascript:

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

正如预期的那样,返回第一个“title”节点的文本。

但是这个

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

返回“未定义”。以下:

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

返回“2”。我不明白。也许当我 selectNodes 它没有得到标题内的文本节点。这是我现在的猜测......这是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>

谢谢

4

3 回答 3

5

selectNodes返回一个数组。

因此,当您编写 时var req=xmlDoc.responseXML.selectNodes("//title"),该req变量包含一个元素数组
由于数组没有text属性,你得到undefined.

相反,您可以编写req[0].text以获取数组中第一个元素的文本。

于 2010-06-25T15:11:00.097 回答
4

selectNodes 返回一个数组而不是单个节点(因此方法的复数命名)。

您可以使用索引器来获取各个节点:

var req=xmlDoc.responseXML.selectNodes("//title");
for (var i=0;i<req.length;i++) {
   alert(req[i].text);
}
于 2010-06-25T15:14:13.547 回答
2

正如方法名所暗示的,selectNodes返回一个集合(数组)。你需要遍历它们。或者,如果您确定结构,请抓住第一个元素。

于 2010-06-25T15:13:33.373 回答