I\'m trying to figure out how QXmlStreamReader works for a C++ application I\'m writing. The XML file I want to parse is a large dictionary with a convoluted structure and plent
Try this Example i just copied it from my project it work for me.
void MainWindow::readXML(const QString &fileName)
{
fileName = "D:/read.xml";
QFile* file = new QFile(fileName);
if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::critical(this, "QXSRExample::ReadXMLFile", "Couldn't open xml file", QMessageBox::Ok);
return;
}
/* QXmlStreamReader takes any QIODevice. */
QXmlStreamReader xml(file);
/* We'll parse the XML until we reach end of it.*/
while(!xml.atEnd() && !xml.hasError())
{
/* Read next element.*/
QXmlStreamReader::TokenType token = xml.readNext();
/* If token is just StartDocument, we'll go to next.*/
if(token == QXmlStreamReader::StartDocument)
continue;
/* If token is StartElement, we'll see if we can read it.*/
if(token == QXmlStreamReader::StartElement) {
if(xml.name() == "email") {
ui->listWidget->addItem("Element: "+xml.name().toString());
continue;
}
}
}
/* Error handling. */
if(xml.hasError())
QMessageBox::critical(this, "QXSRExample::parseXML", xml.errorString(), QMessageBox::Ok);
//resets its internal state to the initial state.
xml.clear();
}
void MainWindow::writeXML(const QString &fileName)
{
fileName = "D:/write.xml";
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::critical(this, "QXSRExample::WriteXMLFile", "Couldn't open anna.xml", QMessageBox::Ok);
return;
}
QXmlStreamWriter xmlWriter(&file);
xmlWriter.setAutoFormatting(true);
xmlWriter.writeStartDocument();
//add Elements
xmlWriter.writeStartElement("bookindex");
ui->listWidget->addItem("bookindex");
xmlWriter.writeStartElement("Suleman");
ui->listWidget->addItem("Suleman");
//write all elements in xml filexl
xmlWriter.writeEndDocument();
file.close();
if (file.error())
QMessageBox::critical(this, "QXSRExample::parseXML", file.errorString(), QMessageBox::Ok);
}