当前位置: 代码迷 >> QT开发 >> xml解析中QDomDocument的setContent方法报错,该如何解决
  详细解决方案

xml解析中QDomDocument的setContent方法报错,该如何解决

热度:98   发布时间:2016-04-25 03:22:05.0
xml解析中QDomDocument的setContent方法报错
接触Qt不久,今天要做一个结果列表,就采用了xml,然后就用Qt的DOM来解析,结果发现,每次执行到QDomDocument的setContent方法都要报错,贴代码:

xml文件:recordshistoryrecords.xml

<?xml version="1.0" encoding="UTF-8" ?>
<historyrecords>
<record id="01">
<injectamount>100</injectamount>
<speedtime>0.5</speedtime>
<psi>1200</psi>
<time>0.6</time>
<status>good</status>
</record>
<record id="02">
<injectamount>110</injectamount>
<speedtime>0.6</speedtime>
<psi>1100</psi>
<time>0.3</time>
<status>bad</status>
</record>
</historyrecords>


解析xml文件的代码:

void historyrecords::showhisrecords() {

    QDomDocument doc;
    QFile file("recordshistoryrecords.xml");
    QString errorStr;
    int errorLine;
    int errorCol;
    //setContent是将指定的内容指定给QDomDocument解析,
    //第一参数可以是QByteArray或者是文件名等
    if(!doc.setContent(&file,true,&errorStr,&errorLine,&errorCol))
    {
        //如果出错,则会进入这里。errorStr得到的是出错说明
        //errorLine和errorCol则是出错的行和列
        qDebug() << errorStr << "line: " << errorLine << "col: " << errorCol;
    }

    QDomNode firstNode = doc.firstChild();

    qDebug() << qPrintable(firstNode.nodeName()) << qPrintable(firstNode.nodeValue());

}


每次报错都会报:
"error occurred while parsing element" line:  1 col:  1

很无语啊,我把xml都检查了好多次,怎么都不对,就是过不去,希望大侠帮着看看,谢谢了!
------解决方案--------------------

void historyrecords::showhisrecords() {

    QDomDocument doc;
    QFile file("recordshistoryrecords.xml");
    file.open(QIODevice::ReadOnly);
    QString errorStr;
    int errorLine;
    int errorCol;
    //setContent是将指定的内容指定给QDomDocument解析,
    //第一参数可以是QByteArray或者是文件名等
    if(!doc.setContent(&file,true,&errorStr,&errorLine,&errorCol))
    {
        //如果出错,则会进入这里。errorStr得到的是出错说明
        //errorLine和errorCol则是出错的行和列
        qDebug() << errorStr << "line: " << errorLine << "col: " << errorCol;
    }
    file.close();

    QDomNode firstNode = doc.firstChild();

    qDebug() << qPrintable(firstNode.nodeName()) << qPrintable(firstNode.nodeValue());

}