从 XMLHttpRequest 解析 XML
我正在使用 QML 和 XMLHttpRequest 来获取一些 XML 数据。
var doc = new XMLHttpRequest();
if (doc.readyState == XMLHttpRequest.DONE) {
var root = doc.responseXML.documentElement;
// Go through recenttracks children
var recentTracks = root.childNodes[1];
for (var i=0; i < recentTracks.childNodes.length; ++i)
{
var child = recentTracks.childNodes[i];
for (var j=0; j < child.childNodes.length; ++j)
{
if (child.childNodes[j].nodeName == "name")
{
console.log(child.childNodes[j].nodeValue); // [!]
}
}
}
}
例如,我正在解析这样的 XML。
<track>
<artist mbid="293f35f8-3682-44bd-9471-13ca94fa9560">Tyler James</artist>
<name>Tried To Measure</name>
<streamable>0</streamable>
<album mbid="">It Took The Fire</album>
<url>http://www.last.fm/music/Tyler+James/_/Tried+To+Measure</url>
<image size="small">http://userserve-ak.last.fm/serve/34s/59408859.jpg</image>
</track>
现在看一下代码[!]
中的注释。在该行之前,我检查当前节点名称是否为“name”(查看 XML)。现在我想获取 name
值。我写的是:child.childNodes[j].nodeValue
,但它 10 次都返回 null(有 10 个子节点)。怎么了?
I'm using QML and XMLHttpRequest for fetching some XML-data.
var doc = new XMLHttpRequest();
if (doc.readyState == XMLHttpRequest.DONE) {
var root = doc.responseXML.documentElement;
// Go through recenttracks children
var recentTracks = root.childNodes[1];
for (var i=0; i < recentTracks.childNodes.length; ++i)
{
var child = recentTracks.childNodes[i];
for (var j=0; j < child.childNodes.length; ++j)
{
if (child.childNodes[j].nodeName == "name")
{
console.log(child.childNodes[j].nodeValue); // [!]
}
}
}
}
I'm parsing, for example, such XML.
<track>
<artist mbid="293f35f8-3682-44bd-9471-13ca94fa9560">Tyler James</artist>
<name>Tried To Measure</name>
<streamable>0</streamable>
<album mbid="">It Took The Fire</album>
<url>http://www.last.fm/music/Tyler+James/_/Tried+To+Measure</url>
<image size="small">http://userserve-ak.last.fm/serve/34s/59408859.jpg</image>
</track>
Now look at comment in code [!]
. Before that line I'm checking whether current node name is "name" (look at XML). Now I want to get name
value. I wrote: child.childNodes[j].nodeValue
, but it returns null all 10 times (there are 10 children). What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DOM 中元素节点的文本由子元素(文本节点)表示。文本节点的值就是您想要的。
因此更改
为
使其工作。
请参阅 http://www.w3schools.com/dom/dom_nodes_get.asp
也许还可以考虑使用 XmlListModel。
The text of an element node in the DOM is represented by a child element (a text node). The value of the text node is what you want.
So change
into
to make it work.
See http://www.w3schools.com/dom/dom_nodes_get.asp
Maybe also consider using a XmlListModel.