QFile按行读取分割xml文件

xml文件很大时不方便操作
按行读取切割xml文件

枚举值 描述
QIODevice::NotOpen 未打开
QIODevice::ReadOnly 以只读方式打开
QIODevice::WriteOnly 以只写方式打开
QIODevice::ReadWrite 以读写方式打开
QIODevice::Append 以追加的方式打开,新增加的内容将被追加到文件末尾
QIODevice::Truncate 以重写的方式打开,在写入新的数据时会将游标设置在文件开头
QIODevice::Text 在读取时,将行结束符转换成 \n;在写入时,将行结束符转换成本地格式,例如 Win32 平台上是 \r\n
QIODevice::Unbuffered 忽略缓存

xml文件示例


	GeorgeJohnReminder
GeorgeJohnReminder
GeorgeJohnReminder
#include 
#include 
#include 
#include 
#include 
#include 
#include 

void splitXmlFile();
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    splitXmlFile();
    return a.exec();
}

/*
 * 读取当前目录下dump.xml
 * 分割成小xml文件在split下
*/
void splitXmlFile()
{
    QDir tempDir;
    QString currentDir = tempDir.currentPath();
    qDebug() << currentDir;
    QString baseFile = currentDir + "/dump.xml";

    // 
    QString dbStart = "";
    QString dbName;

    // 
    QString tableStart = "
"; QString tableFinish = "
"; QString tableName; // 创建输出目录 QString outputPath = currentDir + "/split"; tempDir.mkpath(outputPath); QFile *basefile = new QFile(baseFile); if(!basefile->open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "open failed."; return; } // 获取根标签名字 while(!basefile->atEnd()) { QByteArray line = basefile->readLine(); QString lineStr(line); if(lineStr.contains(dbStart)) { qDebug() << "contain dbstart : " << lineStr; int dbNameStartPos = lineStr.indexOf(dbStart) + dbStartLen; int dbNameLen = lineStr.indexOf(dbEnd) - dbNameStartPos; dbName = lineStr.mid(dbNameStartPos, dbNameLen); qDebug() << "db name : " << dbName; break; } } // 获取子标签 QString tableFile = outputPath + "/" + dbName + "#"; while(!basefile->atEnd()) { QByteArray line = basefile->readLine(); QString lineStr(line); if(lineStr.contains(tableStart)) { int tableNameStartPos = lineStr.indexOf(tableStart) + tableStartLen; int tableNameLen = lineStr.indexOf(tableEnd) - tableNameStartPos; tableName = lineStr.mid(tableNameStartPos, tableNameLen); QString tableFile = outputPath + "/" + dbName + "#" + tableName; QFile *inputfile = new QFile(tableFile); if(!inputfile->open(QIODevice::WriteOnly | QIODevice::Truncate)) { basefile->close(); qDebug() << "open file failed."; return; } QTextStream stream(inputfile); stream << lineStr; while(!basefile->atEnd()) { line = basefile->readLine(); lineStr = line; stream << lineStr; if(lineStr.contains(tableFinish)) { stream.flush(); inputfile->close(); break; } } } } basefile->close(); qDebug() << "end."; }

你可能感兴趣的:(c++)