ChildNodes/NodeValue 混淆

发布于 2024-11-19 06:37:29 字数 652 浏览 3 评论 0原文

我是 Ajax 新手。

我正在尝试解析此文档

我已经了解了readystatechange,它正在获取XML。但当涉及到 childNode 及其值时,我感到很困惑。

这是一些代码。如果我尝试提醒第一个值,它会显示为空白。

var clientList = request.responseXML.getElementsByTagName('client');
for (var i=0;i<clientList.length;i++) {
    var client=clientList[i];
    var clientName = client.childNodes[0].nodeValue;
    alert(clientName)

据我了解,根据 XML 文档,每个“客户端”标签都将具有以下子节点:

[0] : clientName, 
[1] : clientStreetAddress, 
[2] : clientCity
[n] : ...and so on... 

那么我在这里缺少什么?显然我没有掌握事实。请帮忙!

I'm new with Ajax.

I'm trying to parse this document.

I've gotten as far as the readystatechange, and it's fetching the XML. But I get confused when it comes to the childNodes and their values.

Here's a bit of the code. If I try to alert that first value, it comes up blank.

var clientList = request.responseXML.getElementsByTagName('client');
for (var i=0;i<clientList.length;i++) {
    var client=clientList[i];
    var clientName = client.childNodes[0].nodeValue;
    alert(clientName)

As far as I understand it, based on the XML document, each "client" tag would have the following ChildNodes:

[0] : clientName, 
[1] : clientStreetAddress, 
[2] : clientCity
[n] : ...and so on... 

So what am I missing here? Clearly I don't have my facts straight. Please help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人│生佛魔见 2024-11-26 06:37:29

您应该使用标签名称从 XML 中读取数据,而不是根据它们的顺序。解析文档时,它可能包含元素之间空白的文本节点,这会偏移包含所需数据的元素的索引。

var clientName = client.childNodes.selectSingleNode('./clientName').nodeValue;

You should read the data from the XML using the names of the tags, not based on what order they happen to be. When the document is parsed it might contain textnodes for the whitespace between the elements, which would offset the indexes of the elements containing the data that you want.

var clientName = client.childNodes.selectSingleNode('./clientName').nodeValue;
筱武穆 2024-11-26 06:37:29

感谢 TeslaNick 建议我使用 XPATH。答案如下:

var clientDoc = request.responseXML;
var clientName = clientDoc.evaluate("data/client[1]/clientName", clientDoc, null, XPathResult.STRING_TYPE, null).stringValue

当然,我认为必须修改它以处理 IE 浏览器,并且必须将路径设置为循环通过客户端。然而,实际的、最简单的答案就在上面。

也感谢 Guffa 的帮助!

Thanks to TeslaNick for suggesting I use XPATH instead. The answer was as follows:

var clientDoc = request.responseXML;
var clientName = clientDoc.evaluate("data/client[1]/clientName", clientDoc, null, XPathResult.STRING_TYPE, null).stringValue

Of course, I think this has to be modified to handle IE browsers, and the path has to be set to loop through the clients. However, the actual, simplest answer is above.

Thanks also to Guffa for helping!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文