This is the QXmlStreamReader version. This example will create an output like the following:
-----start----
[ElementName]
[Attribute = Value, ...]
[ElementText if existing]
-----end-----
The bool flag is necessary since reader.readElementText() raises an error if there is no element text. The stream reader version should have very good performance.
QFile sourceFile
("source.xml");
if( !sourceFile.
open( QIODevice::ReadOnly ) ) return;
QFile targetFile
("output.txt");
if( !targetFile.
open( QIODevice::WriteOnly ) ) return;
QXmlStreamReader reader(&sourceFile);
bool lastElementHadText = true;
while( !reader.atEnd() ) {
reader.readNext();
if( reader.isStartElement() ) {
if( !lastElementHadText )
writer << "-----end-----" <<endl;
writer << "-----start-----" << endl;
writer << reader.name().toString() << endl;
foreach( QXmlStreamAttribute attribute, reader.attributes() ) {
writer << attribute.name().toString() << "=" << attribute.value().toString() << ", ";
}
if( reader.attributes().count() > 0 )
writer << endl;
}
if( reader.isCharacters() && !reader.isWhitespace() ) {
lastElementHadText = true;
writer << reader.text().toString() << endl;
writer << "-----end-----" <<endl;
}
}
writer.flush();
targetFile.close();
sourceFile.close();
QFile sourceFile("source.xml");
if( !sourceFile.open( QIODevice::ReadOnly ) )
return;
QFile targetFile("output.txt");
if( !targetFile.open( QIODevice::WriteOnly ) )
return;
QXmlStreamReader reader(&sourceFile);
QTextStream writer(&targetFile);
bool lastElementHadText = true;
while( !reader.atEnd() ) {
reader.readNext();
if( reader.isStartElement() ) {
if( !lastElementHadText )
writer << "-----end-----" <<endl;
writer << "-----start-----" << endl;
writer << reader.name().toString() << endl;
foreach( QXmlStreamAttribute attribute, reader.attributes() ) {
writer << attribute.name().toString() << "=" << attribute.value().toString() << ", ";
}
if( reader.attributes().count() > 0 )
writer << endl;
}
if( reader.isCharacters() && !reader.isWhitespace() ) {
lastElementHadText = true;
writer << reader.text().toString() << endl;
writer << "-----end-----" <<endl;
}
}
writer.flush();
targetFile.close();
sourceFile.close();
To copy to clipboard, switch view to plain text mode
greetings
Bookmarks