0

我有一个如下所示的 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?我该如何解决?

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

4

1 回答 1

0

您获取ServiceExceptionxml 节点的 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);

于 2017-04-15T13:28:30.553 回答