下面这段代码为什么解析不出来</firstName>和</lastName>呢?
- C/C++ code
#include <QtCore/QCoreApplication>#include <QtCore/QFile>#include <QtCore/QXmlStreamReader>#include <QtCore/QDebug>int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); QString firstName=""; QString lastName=""; QString filePath = "D://Share//Qt//xmlreader//xmlreader//xmlreader.xml"; QFile xmlFile(filePath); qDebug()<<xmlFile.open(QIODevice::ReadOnly); QXmlStreamReader xmlReader(xmlFile.readAll()); xmlReader.readNext(); qDebug()<<xmlReader.name(); xmlReader.readNext(); qDebug()<<xmlReader.name(); while(!xmlReader.atEnd()) { if(xmlReader.isStartElement()) { if(xmlReader.name()=="firstName") { qDebug()<<xmlReader.name(); firstName+=xmlReader.readElementText(); } if(xmlReader.name()=="lastName") { qDebug()<<xmlReader.name(); lastName+=xmlReader.readElementText(); } } else if(xmlReader.isEndElement()) { qDebug()<<QString("%1%2").arg("/").arg(xmlReader.name().toString()); xmlReader.readNext(); } xmlReader.readNext(); } qDebug()<<QString("%1 %2").arg(firstName).arg(lastName);}
xml文件的内容如下:
- XML code
<?xml version="1.0" encoding="UTF-8"?><fullName> <firstName>first</firstName> <lastName>last</lastName></fullName>
运行结果如下:
""
"fullName"
"firstName"
"lastName"
"/fullName"
"first last"
大家帮我看看吧
------解决方案--------------------
- C/C++ code
QXmlStreamReader xml(xmlFile.readAll()); while (!xml.atEnd()) { xml.readNext(); if(xml.error()) { qDebug()<<"error:"; qDebug()<<xml.errorString(); } if (xml.tokenType() == QXmlStreamReader::StartElement) { qDebug()<<"start:"; qDebug()<<xml.name(); } if (xml.tokenType() == QXmlStreamReader::EndElement) { qDebug()<<"end:"; qDebug()<<xml.name(); } }