7
一個XML文件,比方說,我有一個這樣的XML文件:解析Qt中
<?xml version="1.0" encoding="utf-8"?>
<name>
<id>1</id>
</name>
我如何分析它,並得到id
價值?
std::string id = ...;
一個XML文件,比方說,我有一個這樣的XML文件:解析Qt中
<?xml version="1.0" encoding="utf-8"?>
<name>
<id>1</id>
</name>
我如何分析它,並得到id
價值?
std::string id = ...;
像這樣將工作:
xmlFile = new QFile("xmlFile.xml");
if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::critical(this,"Load XML File Problem",
"Couldn't open xmlfile.xml to load settings for download",
QMessageBox::Ok);
return;
}
xmlReader = new QXmlStreamReader(xmlFile);
//Parse the XML until we reach end of it
while(!xmlReader->atEnd() && !xmlReader->hasError()) {
// Read next element
QXmlStreamReader::TokenType token = xmlReader->readNext();
//If token is just StartDocument - go to next
if(token == QXmlStreamReader::StartDocument) {
continue;
}
//If token is StartElement - read it
if(token == QXmlStreamReader::StartElement) {
if(xmlReader->name() == "name") {
continue;
}
if(xmlReader->name() == "id") {
qDebug() << xmlReader->readElementText();
}
}
}
if(xmlReader->hasError()) {
QMessageBox::critical(this,
"xmlFile.xml Parse Error",xmlReader->errorString(),
QMessageBox::Ok);
return;
}
//close reader and flush file
xmlReader->clear();
xmlFile->close();
我做了@書士的回答的簡化版本。而不是從文件中讀取我剛從一個QString的可變的讀取和我刪除了continue;
塊:
QString xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<name>\n"
" <id>1</id>\n"
"</name>\n";
QXmlStreamReader reader(xml);
while(!reader.atEnd() && !reader.hasError()) {
if(reader.readNext() == QXmlStreamReader::StartElement && reader.name() == "id") {
qDebug() << reader.readElementText();
}
}
我沒有看到這裏的任何XML .. – liaK 2010-06-22 11:01:26
谷歌提供此鏈接:http://www.digitalfanatics.org/項目/ qt_tutorial/chapter09.html。這對你有幫助嗎? – stefaanv 2010-06-22 11:18:45