testus
testus

Reputation: 183

QtNetwork: Download xml file and read its content

I have a Qt application where I am trying to download a XML file form a server and then read the content of the file. Unfortunately, I am not able to get the content of the downloaded file in to a QDomDocument.

This is what I tried

QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileIsReady(QNetworkReply*)) );
manager->get(QNetworkRequest(QUrl("http://example.com/file.xml")));


fileIsReady(QNetworkReply *reply){

    QTemporaryFile tempFile;
    if(tempFile.open()){
        tempFile.write(reply->readAll());
        QDomDocument versionXML;
        QDomElement root;

        if(!versionXML.setContent(&tempFile)){
            qDebug() << "failed to load version file" << endl;
        }
        else{
            root=versionXML.firstChildElement();
            //...
        }

    }

}

How can I achieve this?

Upvotes: 0

Views: 1346

Answers (1)

Simon Warta
Simon Warta

Reputation: 11418

I think the streaming interfaces are a bit hard to use when you are new to Qt. If you don't have super-big downloads that fit into RAM, just use QByteArray.

fileIsReady(QNetworkReply *reply){
    QByteArray data = reply->readAll();
    qDebug() << "XML download size:" << data.size() << "bytes";
    qDebug() << QString::​fromUtf8(data);

    QDomDocument versionXML;

    if(!versionXML.setContent(data))
    {
        qWarning() << "Failed to parse XML";
    }

    // ...
}

Upvotes: 1

Related Questions