检查XML中的异常

时间:2017-04-15 11:02:04

标签: xml qt qdomdocument

我有一个XML文件,如下所示:

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

我已经创建了这样的代码:

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>"); 
    }
}

程序将其写入textEdit:

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

为什么def没有显示在textEdit中?我该如何解决这个问题?

顺便说一句。对不起我的英文

1 个答案:

答案 0 :(得分:0)

您获取ServiceException xml节点的QDomElement的方式不匹配。

以下代码:

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

应该替换为这样的东西:

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

在您的代码中,您尝试迭代QDomNodeList exceptions列表,但在循环中,您调用了report.item(i)而不是exceptions.item(i);