2010-06-22 35 views
7

Hãy nói rằng tôi có một tập tin XML như thế này:Phân tích một file XML trong Qt

<?xml version="1.0" encoding="utf-8"?> 
<name> 
    <id>1</id> 
</name> 

Làm thế nào tôi có thể phân tích nó và nhận được giá trị của id?

std::string id = ...; 
+0

Tôi không thấy bất kỳ XML ở đây .. – liaK

+4

google cung cấp liên kết này: http://www.digitalfanatics.org/ projects/qt_tutorial/chapter09.html. Điều này có giúp bạn không? – stefaanv

Trả lời

16

Something như thế này sẽ làm việc:

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(); 
0

tôi đã thực hiện một phiên bản đơn giản của @ câu trả lời Scrivener của. Thay vì đọc từ một tập tin tôi chỉ đọc từ một biến QString và tôi loại bỏ các continue; khối:

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(); 
    } 
}