Disons que j'ai un fichier XML comme ceci:analyser un fichier XML dans Qt
<?xml version="1.0" encoding="utf-8"?>
<name>
<id>1</id>
</name>
Comment puis-je analyser et obtenir la valeur de id
?
std::string id = ...;
Disons que j'ai un fichier XML comme ceci:analyser un fichier XML dans Qt
<?xml version="1.0" encoding="utf-8"?>
<name>
<id>1</id>
</name>
Comment puis-je analyser et obtenir la valeur de id
?
std::string id = ...;
Quelque chose comme cela fonctionnera:
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();
J'ai fait une version simplifiée de @ réponse de Scrivener. Au lieu de lire à partir d'un fichier que je viens de lire à partir d'une variable QString et j'ai enlevé les blocs 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();
}
}
Je ne vois pas XML ici .. – liaK
google a fourni ce lien: http://www.digitalfanatics.org/ projects/qt_tutorial/chapter09.html. Cela vous aide-t-il? – stefaanv