My fellow Qt enthusiasts,
I have a parser class that inherits QXmlStreamReader. The class is supposed to do two things: 1) parse the contents of the file. 2) determine the 'type' of xml file (getType(..) ).
I would like for the getType()-method to read only as far into the file as necessary before returning with the type. That is to say, i want to read as little as possible of the file to determine its type.
The problem is that after returning the type and aborting the read, the subsequent attempt to read the entire file fails with "premature end of document". I have tried using QXmlStreamReader::clear(), i've tried QIODevice::reset(), QIODevice::seek(0), none of them manage to reset the device properly. QIODevice::pos() returns 0 after each of the above operations and yet it does not seem to be properly reset.
If i create two instances of Parser, and let one do getType and the other parse the IODevice, then it works. But it's a cheap victory since it's not behaving the way i want. What am i doing wrong?
Example:
I have two types of xml-files, each identifiable by the root-tag:
and
My getType() method looks something like this:
{
setDevice(device);
while (!atEnd()){
readNext();
if (isStartElement()){
if (name() == "typeA"){
return TypeA;
}else if (name() == "typeB"){
return TypeB;
}else{
return UnknownType;
}
}
}
return UnknownType;
}
FileType Parser::getType(QIODevice* device)
{
setDevice(device);
while (!atEnd()){
readNext();
if (isStartElement()){
if (name() == "typeA"){
return TypeA;
}else if (name() == "typeB"){
return TypeB;
}else{
return UnknownType;
}
}
}
return UnknownType;
}
To copy to clipboard, switch view to plain text mode
My read()-method is simple:
{
setDevice(device);
while (!atEnd()){
readNext();
cout << "token: " << tokenString().toStdString() << endl;
}
return !error();
}
bool Parser::read(QIODevice* device)
{
setDevice(device);
while (!atEnd()){
readNext();
cout << "token: " << tokenString().toStdString() << endl;
}
return !error();
}
To copy to clipboard, switch view to plain text mode
My calling method looks like this:
cout << "error" << endl;
return;
}
Parser reader;
FileType type = reader.getType(&file);
if (type == TypeA){
reader.read(&file);
}
file.close();
QFile file(fileName);
if (!file.open(QFile::ReadOnly | QFile::Text)){
cout << "error" << endl;
return;
}
Parser reader;
FileType type = reader.getType(&file);
if (type == TypeA){
reader.read(&file);
}
file.close();
To copy to clipboard, switch view to plain text mode
As always, thanks in advance!
Bookmarks