How to use QXmlStreamReader to parse well-formed XML, Qt's documentation states that it is a faster and more convenient alternative to Qt's own SAX parser (QXmlSimpleReader), it is also faster, in some cases It is more convenient than DOM (QDomDocument).
XML file:
Parsing method:
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()); }
The above is the detailed content of Sample code sharing for Qt parsing XML. For more information, please follow other related articles on the PHP Chinese website!