问题描述
我正在使用QML和XMLHttpRequest来获取一些XML数据.
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); // [!]
}
}
}
}
例如,我正在解析 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>
现在查看代码[!]
中的注释.在那行之前,我正在检查当前节点名称是否为名称"(查看XML).现在我想获取name
值.我写了:child.childNodes[j].nodeValue
,但是它全部返回空10次(有10个孩子).怎么了?
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?
推荐答案
DOM中元素节点的文本由子元素(文本节点)表示.文本节点的值就是您想要的.
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.
所以改变
child.childNodes[j].nodeValue
进入
child.childNodes[j].childNodes[0].nodeValue
使其正常工作.
请参见 http://www.w3schools.com/dom/dom_nodes_get.asp
也许还考虑使用XmlListModel.
Maybe also consider using a XmlListModel.
这篇关于从XMLHttpRequest解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!