Why can't I parse a XML file using QXmlStreamReader from Qt?

后端 未结 5 1785
长发绾君心
长发绾君心 2021-02-14 06:43

I\'m trying to figure out how QXmlStreamReader works for a C++ application I\'m writing. The XML file I want to parse is a large dictionary with a convoluted structure and plent

5条回答
  •  遇见更好的自我
    2021-02-14 06:53

    I'm answering this myself as this problem was related to three issues, two of which were brought up by the responses.

    1. The file actually wasn't UTF-8 encoded. I changed the encoding to iso-8859-1 and the encoding warning disappeared.
    2. The text() function doesn't work as I expected. I have to use readElementText() to read the entries' contents.
    3. When I try to readElementText() on an element that doesn't contain text, like the top-level in my case, the parser returns an "Expected character data" error and the parsing is interrupted. I find this behaviour strange (in my opinion returning an empty string and continuing would be better) but I guess as long as the specification is known, I can work around it and avoid calling this function on every entry.

    The relevant code section that works as expected now looks like this:

    while (!xml.atEnd() && !xml.hasError()) 
    {
        xml.readNext();
        if (xml.isStartElement())
        {
            QString name = xml.name().toString();
            if (name == "firstname" || name == "surname" || 
                name == "email" || name == "website")
            {
                cout << "element name: '" << name  << "'" 
                             << ", text: '" << xml.readElementText() 
                             << "'" << endl;
            }
        }
    }
    if (xml.hasError())
    {
        cout << "XML error: " << xml.errorString() << endl;
    }
    else if (xml.atEnd())
    {
        cout << "Reached end, done" << endl;
    }
    

提交回复
热议问题