检查 XML 中的异常

Checking for exception in XML

我有一个 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>"); 
    }
}

程序在文本编辑中写入:

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

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

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

您为 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);