QT: QXmlStreamReader always returns “Premature End of Document” error

心已入冬 提交于 2019-12-23 16:19:05

问题


I have strange issue with Qt QXmlStreamReader. I'am trying to parse simple document (note: it is generated using QXmlStreamWriter):

<?xml version="1.0" encoding="UTF-8"?>
<tex>
    <used_by/>
    <facade>
        <tags>
            <town_related></town_related>
            <zone_related></zone_related>
            <visual_related></visual_related>
            <kind_related></kind_related>
            <other>flamingo</other>
        </tags>
        <additional_textures>
            <id>flamingo_top.psd</id>
        </additional_textures>
    </facade>
</tex>

Using this code:

QFile file(filename);
if (file.open(QFile::ReadOnly | QFile::Text))
{
    QXmlStreamReader xmlReader(&file);

    while (xmlReader.readNextStartElement())
    {
        /* same issue when uncommented: 
        if (xmlReader.name() == "tex")
            t->readXml(xmlReader);//parse texture
        else*/
            xmlReader.skipCurrentElement();
    }

    if (xmlReader.hasError())
        emit reportError(xmlReader.errorString());
}
...

And it always reports error "Premature end of document". Why? When debbuging, it seems, to all elements are parsed or skipped correctly.


回答1:


I verified the behavior of your code. Indeed, it seems that readNextStartElement() does not correctly check for end of document. It only checks for start/end element to return its value, so if reading past the end of document, its internal call to readNext raises "premature end".

For a quick fix try checking for end of document yourself using readNext(), eg.:

    while (!xml.atEnd()) {
        if (xml.readNext() != QXmlStreamReader::EndDocument) {
            if (xml.isStartElement())
                std::cout << qPrintable(xml.name().toString()) << std::endl;
        }
    }

    if (xml.hasError())
        std::cout << (xml.errorString().toUtf8().constData()) << std::endl;


来源:https://stackoverflow.com/questions/46346450/qt-qxmlstreamreader-always-returns-premature-end-of-document-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!