JavaScript:

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

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

但是这个

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

返回“未定义”。以下:

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

返回“ 2”我不明白。也许当我选择nodes时,它不会在标题中获取文本节点。那是我现在的猜测...这是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>

谢谢

有帮助吗?

解决方案

SelectNodes返回一个阵列而不是单个节点(因此该方法的复数命名)。

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

var req=xmlDoc.responseXML.selectNodes("//title");
for (var i=0;i<req.length;i++) {
   alert(req[i].text);
}

其他提示

selectNodes 返回一个数组。

因此,当你写 var req=xmlDoc.responseXML.selectNodes("//title"), , 这 req 可变含量为 大批 元素。
由于数组没有 text 财产,你得到了 undefined.

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

正如方法名称所建议的那样, selectNodes 返回集合(数组)。您需要循环浏览它们。或者,如果您确定结构,请抓住第一个元素。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top