PDA

View Full Version : Parse xml file using QStreamReader



Gary.zhang
10th January 2011, 05:00
Hello everybody,

I'm trying to parse a Xml file using QStreamReader, first time, I put the code in the main function like this:


QFile *file = new QFile(":/source/qk.xml");
//Test the qk.xml is opened or not..
if(!file->open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox :: information(NULL,"XML-information","Xml open faile.",
QMessageBox::Yes | QMessageBox :: No,
QMessageBox::Yes);
}

QXmlStreamReader xml(file);

while(!xml.atEnd())
{
if(xml.isStartElement() && xml.name()=="salary")
{
QXmlStreamAttributes attrs = xml.attributes();
//---
QStringRef fName = attrs.value("normalsalary");
QStringRef sName = attrs.value("otsalary");

if(fName.isEmpty())
{
xml.readNext();
continue;
}
QString bb="Normal-Salary is ";
bb.append(fName.toString());
bb.append(",OT-Salary is ");
bb.append(sName.toString());
QMessageBox::information(NULL,"XML-information",bb,QMessageBox::Ok);
}
else if(xml.isEndElement() && xml.name() == "persons")
{
//if EndElement is persons then stop the loop and create UI
}
xml.readNext();
}
*/

the reference xml file like this:

<?xml version="1.0" encoding="UTF-8" ?>
<setting>

<salary normalsalary="800" otsalary="1500" />

</setting>


until here,all the thing works prefectly, and then I put the Parse function in a class named XmlManager,However ,when I test the Class, It return me an error -"Premature end of document"
there is the fallow class function GetSettingValue()


QString XmlManager::GetSettingValue(QString mothernode, QString childnode)
{

QFile *file = new QFile(":/source/qk.xml");

QXmlStreamReader xml(file);
QString ww;


while(!xml.atEnd())
{
if(xml.isStartElement() && xml.name()=="salary")
{
QXmlStreamAttributes attrs = xml.attributes();
//---
QStringRef fName = attrs.value("normalsalary");
QStringRef sName = attrs.value("otsalary");
i=1000;
if(fName.isEmpty())
{
xml.readNext();
continue;
}
}
else if(xml.isEndElement() && xml.name() == "persons")
{
//if EndElement is persons then stop the loop and create UI
}
xml.readNext();
}
ww=xml.errorString();
return ww;
}


can any body give me a suggestion? Thanks.

Added after 42 minutes:

Sorry everybody, I found i make a stupid question, the reason I can't Parse the xml's context using a class is that ,I just never open the file , which I just forgot 'file->open..' ,,Oh,It waste me a whole day.....