Parse XML from XMLHttpRequest

2019-02-27 12:03发布

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?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-27 12:53

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

child.childNodes[j].nodeValue

into

child.childNodes[j].childNodes[0].nodeValue

to make it work.

See http://www.w3schools.com/dom/dom_nodes_get.asp

Maybe also consider using a XmlListModel.

查看更多
登录 后发表回答