Domanda

I want to get my retrieved xmlHttpRequest object into an XMLListModel. I am using qml. The main goal is to evaluate the xml I get and show the entries in a list. If there's a better method - let me know.

I found a "solution" here for analyzing the xml: http://developer.nokia.com/Community/Discussion/showthread.php/232839-Qt-Quick-and-DOM-doc-responseXML-returns-null and here Parse XML from XMLHttpRequest But it is VERY poor to dig in deep xml structures, because there are loops arround every level of the xml tree.

So the 2 ways I would like to have:

1: XmlList

This would be my favourite: parse the data I got from the xmlHttpRequest to a XmlList thing and get the list for free (automatically). This guy wanted the same, but didn't write out a solution: http://qt-project.org/forums/viewthread/6460

I also tried:

XmlListModel{id: xmlModel}
...
xmlModel.xml = xhr.responseXML;

The first one separately, and the last line, where I get the xml. This says "Error: Cannot assign null to QString". I am sure, that I get a correct xml answer, because the above mentioned method with searching for each child and the tagname is working. Also I found a different notation with something like a parser, but that didn't work either.

2: XPath

var doc = new DOMParser().parseFromString(response, "text/xml"); returnes DOMParser not defined .. so I guess I would need some library there, but didn't find anything about the topic (else than unanswered questions). (Same with .getElementById and evaluateXPath and many other thing I found on the net)

Any hint is appreciated!

È stato utile?

Soluzione

The xml property of XmlListModel must be of type string. Therefore you have to assign xhr.responseText instead of xhr.responseXML. Here is a minimal working example (using a data URI so simulate a server response):

import QtQuick 1.0

ListView {
    width: 200; height: 200

    delegate: Text {
        text: name 
    }

    model: XmlListModel {
        id: xmlModel
        query: "/names/name"

        XmlRole { name: "name"; query: "string()" }
    }

    Component.onCompleted: {
        /*  <names>
                <name>John</name>
                <name>Max</name>
                <name>Sandy</name>
            </names> */
        var dataURI = "data:application/xml;base64,PG5hbWVzPjxuYW1lPkpvaG48L25hbWU+PG5hbWU+TWF4PC9uYW1lPjxuYW1lPlNhbmR5PC9uYW1lPjwvbmFtZXM+"

        var req = new XMLHttpRequest();
        req.onreadystatechange = function () {
            if (req.readyState == 4) {
                xmlModel.xml = req.responseText; //<<<
            }
        };
        req.open("get", dataURI, true);
        req.send();
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top