Question

This is the xml-file:

<?xml version="1.0" encoding="UTF-8"?>
<Text>alpha beta</Text>
<Text>beta gamma</Text>
<Text>gamma delta</Text>
<Text>delta epsilon</Text>
<Text>epsilon golf</Text>

And this is my reader:

QXmlStreamReader inputStream(&dataFile);
        while (!inputStream.atEnd() && !inputStream.hasError())
        {
            inputStream.readNext();
            if (inputStream.isStartElement())
            {
                QString name = inputStream.name().toString();
                if (name == "Text")
                {
                    qDebug()   << "text:" << inputStream.readElementText();
                }
            }
        }

And my qDebug only prints: text: "alpha beta"

Why does it only return one value and how can I correct this?

BR

Was it helpful?

Solution

As Frank correctly noted in the comment, a valid XML document can only have one root element. Once, you fix the data file content, it will work, but I am providing all the content I used during the testing on my machine, anyway.

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<TextList>
<Text>alpha beta</Text>
<Text>beta gamma</Text>
<Text>gamma delta</Text>
<Text>delta epsilon</Text>
<Text>epsilon golf</Text>
</TextList>

main.cpp

#include <QXmlStreamReader>
#include <QDebug>
#include <QString>
#include <QFile>

int main()
{
    QFile file("test.xml");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "File open error:" << file.errorString();
        return 1;
    }
    QXmlStreamReader inputStream(&file);
    while (!inputStream.atEnd() && !inputStream.hasError())
    {
        inputStream.readNext();
        if (inputStream.isStartElement())
        {
            QString name = inputStream.name().toString();
            if (name == "Text")
            {
                qDebug()   << "text:" << inputStream.readElementText();
            }
        }
    }
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

text: "alpha beta" 
text: "beta gamma" 
text: "gamma delta" 
text: "delta epsilon" 
text: "epsilon golf"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top