如何使用QXmlStreamReader来解析格式良好的XML,Qt的文档中指出,它是一种更快、更方便的Qt自己的SAX解析器(QXmlSimpleReader)的替代,它也较快,在某种情况下,比DOM(QDomDocument)更方便。
XML文件:
解析方法:
void ParseXML::parseXML(QString file_name) { if(file_name.isEmpty()) return; QFile *file = new QFile(file_name); if(!file->open(QFile::ReadOnly | QFile::Text)) { QMessageBox::information(NULL, QString("title"), QString("open error!")); return; } //QXmlStreamReader操作任何QIODevice. QXmlStreamReader xml(file); QList> persons; //解析XML,直到结束 while(!xml.atEnd() && !xml.hasError()) { //读取下一个element. QXmlStreamReader::TokenType token = xml.readNext(); //如果获取的仅为StartDocument,则进行下一个 if(token == QXmlStreamReader::StartDocument) { continue; } //如果获取了StartElement,则尝试读取 if(token == QXmlStreamReader::StartElement) { //如果为persons,直接进入下一个 if(xml.name() == "persons") { continue; } //如果为person,则对其进行解析 if(xml.name() == "person") { persons.append(this->parsePerson(xml)); } } } if(xml.hasError()) { QMessageBox::information(NULL, QString("parseXML"), xml.errorString()); } //从reader中删除所有设备、数据,并将其重置为初始状态 xml.clear(); } QMap ParseXML::parsePerson(QXmlStreamReader& xml) { QMap person; //检查是否获取person if(xml.tokenType() != QXmlStreamReader::StartElement && xml.name() == "person") { return person; } //获取person属性 QXmlStreamAttributes attributes = xml.attributes(); if(attributes.hasAttribute("id")) { person["id"] = attributes.value("id").toString(); } //操作下一个 xml.readNext(); while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "person")) { if(xml.tokenType() == QXmlStreamReader::StartElement) { if(xml.name() == "name") { this->addElementDataToMap(xml, person); } if(xml.name() == "age") { this->addElementDataToMap(xml, person); } if(xml.name() == "email") { this->addElementDataToMap(xml, person); } if(xml.name() == "website") { this->addElementDataToMap(xml, person); } } xml.readNext(); } QString id = person["id"]; QString name = person["name"]; QString age = person["age"]; QString email = person["email"]; QString website = person["website"]; return person; } void ParseXML::addElementDataToMap(QXmlStreamReader& xml, QMap& map) const { if(xml.tokenType() != QXmlStreamReader::StartElement) { return; } QString elementName = xml.name().toString(); xml.readNext(); if(xml.tokenType() != QXmlStreamReader::Characters) { return; } map.insert(elementName, xml.text().toString()); }
以上就是 Qt解析XML的示例代码分享的详细内容,更多请关注自由互联其它相关文章!