Javascript selectSingleNode 有效,但 selectNodes 无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3119116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
selectSingleNode works but not selectNodes
提问by Troy
Javascript:
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
返回“2”。我不明白。也许当我选择节点时,它没有在标题中获取文本节点。这是我现在的猜测......这是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>.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>.00</price>
<instock>In Stock</instock>
<notes>no extra info</notes>
</decal>
</catalog>
thanks
谢谢
回答by SLaks
selectNodesreturns an array.
selectNodes返回一个数组。
Therefore, when you write var req=xmlDoc.responseXML.selectNodes("//title"), the reqvariable holds an arrayof elements.
Since arrays do not have a textproperty, you're getting undefined.
因此,当您编写 时var req=xmlDoc.responseXML.selectNodes("//title"),该req变量包含一个元素数组。
由于数组没有text属性,因此您将获得undefined.
Instead, you can writereq[0].textto get the text of the first element in the array.
相反,您可以写入req[0].text以获取数组中第一个元素的文本。
回答by Rob Levine
selectNodes returns an array rather than a single node (hence the plural naming of the method).
selectNodes 返回一个数组而不是单个节点(因此方法的复数命名)。
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);
}
回答by Evan Trimboli
As the method name suggests, selectNodesreturns a collection (array). You need to loop over them. Or if you're sure of the structure, grab the first element.
顾名思义,selectNodes返回一个集合(数组)。你需要遍历它们。或者,如果您确定结构,请获取第一个元素。

