xmlqtqxmlstreamreaderqdomdocument

QDomDocument: setContent error with XML tag


I am trying to set my XML file to QDomDocument using setContent and it returns an error.

My XML file:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <Tag1>
        <Attribute1>5</Attribute1>
        <Attribute2>5</Attribute2>
    </Tag1>
    <Settings\it.server.com>
        <Attribute1>1</Attribute1>
    </Settings\it.server.com>
</root>

Here is a snippet of my code:

QFile file(fileName);

if (file.open(QIODevice::ReadOnly)) {
    QDomDocument domDocument;

    QString errorStr;
    int errorLine;
    int errorColumn;

    if (!domDocument.setContent(&file, false, &errorStr, &errorLine, &errorColumn))
        qDebug() << errorStr << errorLine << errorColumn;
}

The error message I am getting when I run is the following:

error: error occurred while parsing element 7 11

Where row = 7 and column = 11.

Now I'm pretty sure it is probably because of the "\" or "." character in the tag (Settings\it.server.com) that could be causing it to fail. The XML can't be changed because it is from an external source. My question is there anyway around this using QDomDocument?

I have looked into QXmlStreamReader and Writer but I haven't figured out how to update attributes. QDomDocument has better facilities for that.


Solution

  • The XML parser accepts letter, digits, periods, hyphens, etc. You have to remove illegal characters before parsing:

    QFile f(filename);
    if (!f.open(QFile::ReadOnly | QFile::Text)) return;
    
    QTextStream in(&f);
    QString content = in.readAll(); // Get the content
    
    content.replace("\\", "_"); // Remove all '\' char
    
    if (!domDocument.setContent(content, false, &errorStr, &errorLine, &errorColumn))
            qDebug() << errorStr << errorLine << errorColumn;
    

    If your Xml file are huge, you also can create your own QXmlInputSource subclass and replace the illegal characters during the reading (see QXmlInputSource::next())