xmlqtqdomdocument

Checking for exception in XML


I have a XML file that looks like this:

<ServiceExceptionReport>
    <ServiceException>abc</ServiceException>
    <ServiceException>def</ServiceException>
</ServiceExceptionReport>

And i've created code like this:

QDomDocument doc;
doc.setContent(data); // data is QByteArray that contains XML    
QDomNodeList report = doc.elementsByTagName("ServiceExceptionReport");
QDomNodeList exceptions = doc.elementsByTagName("ServiceException");

if (report.isEmpty()){
    ui->textEdit->insertHtml("<font color=\"green\">No exceptions found</font><br>");

} else {
    ui->textEdit->insertHtml("<font color=\"orange\">Found ServiceExceptionReport. Reading ServiceExceptions...</font><br>");
    qDebug() << exceptions.size(); //Program shows 2 here
    for (int i = 0; i < exceptions.size(); i++) {
        QDomNode n = report.item(i);
        QDomElement exception = n.firstChildElement("ServiceException");
        QString number =  QString::number(i);
        QString exceptiontxt = exception.text();
        ui->textEdit->insertHtml("<font color=\"red\">Error no. " + number + "&#58;" + exceptiontxt + "</font><br>"); 
    }
}

Program writes this in the textEdit:

Found ServiceExceptionReport. Reading ServiceExceptions...
Error no. 1 abc
Error no. 2          <-- This is my problem. There should be 'def'

Why def not showing in textEdit? How can i fix that?

btw. Sorry for my English


Solution

  • You have mismatched how you get QDomElement for ServiceException xml node.

    Following lines of you code:

    QDomNode n = report.item(i);
    QDomElement exception = n.firstChildElement("ServiceException");
    

    Should be replaced with something like this:

    QDomNode n = exceptions.item(i);
    QDomElement exception = n.toElement();
    

    In your code, you are trying to iterate over QDomNodeList exceptions list, but in the loop you call report.item(i) instead of exceptions.item(i);