xml:
<?xml version="1.0" encoding="UTF-8"?> <library> <book id="01"> <title>Qt</title> <author>shiming</author> </book> <book id="02"> <title>linux</title> <author>shiming</author> </book> </library>
解析代码:
QFile file(":/my.xml"); if(!file.open(QIODevice::ReadOnly)) { qDebug() << "Error: cannot open file"; return 1; } QXmlStreamReader reader; //设置文件,这时会将流设置为初始状态 reader.setDevice(&file); //如果没有读到文档结尾, 而且没有出现错误 while(!reader.atEnd()) { QXmlStreamReader::TokenType type = reader.readNext(); //下面便根据几号的类型来进行不同的输出 if(type == QXmlStreamReader::StartDocument) { qDebug() << reader.documentEncoding() << reader.documentVersion(); } if(type == QXmlStreamReader::StartElement) { qDebug() << "<" << reader.name() << ">"; if(reader.attributes().hasAttribute("id")) { qDebug() << reader.attributes().value("id"); } } if(type == QXmlStreamReader::EndElement) { qDebug() << "</" << reader.name() << ">"; } if(type == QXmlStreamReader::Characters && !reader.isWhitespace()) { qDebug() << reader.text(); } } //如果读取过程中出现错误,那么请输出错误信息 if(reader.hasError()) { qDebug() << "error" << reader.errorString(); } file.close();输出结果:
"UTF-8" "1.0"
< "library" >
< "book" >
"01"
< "title" >
"Qt"
</ "title" >
< "author" >
"shiming"
</ "author" >
</ "book" >
< "book" >
"02"
< "title" >
"linux"
</ "title" >
< "author" >
"shiming"
</ "author" >
</ "book" >
</ "library" >