QT reads and writes XML files (QXmlStreamWriter and QXmlStreamReader)

There are many ways for Qt to operate XML documents. This article uses QXmlStreamWriter and QXmlStreamReader classes to write and read XML documents.

Use the XML module, add it in the .pro file QT += core xml, and add the corresponding header file #include <QXmlStreamWriter>or #include <QXmlStreamReader>.

QXmlStreamWriter writes XMl documents:

Commonly used functions:

setCodec(): Set encoding encoding, modify the default UTF-8 format

writeStartDocument(): Write the document header, the function is similar to creating an xml document, and write the version information and encoding information at the beginning of the document, the default is:

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

writeEndDocument(): Corresponding writeStartDocument(), when this function is called, it means that the document information has been written.

writeStartElement(): Write start token such as

writeEndElement(): Write end token such as

writeTextElement(): Write text information such as the following name, phone, age, etc.;

Code example:

void xmlWrite()
{
    
    
	QString str[]={
    
    "Amy","Linda","Joan","icy"};
	QString strTime[]={
    
    "20220101","20220815","20221212","20230115"};

	QFile file("./first.xml");
	if(!file.open(QFile::WriteOnly|QFile::Text))
	{
    
    
		qDebug()<< "file cannot open";
		return;
	}

	QXmlStreamWriter stream(&file);
	stream.setAutoFormatting(true);		//自动化格式,提高可读性
	//这里可以分别设置编码、版本1.0。或者直接调用writeStartDocument()默认生成
	//stream.setCodec("gb2312");				// 设置encoding="gb2312"
	//stream.writeStartDocument("1.0", true);	// 开始文档(XML 声明)
	stream.writeStartDocument();				// 默认: <?xml version="1.0" encoding="UTF-8"?>	
	stream.writeStartElement("DATA");

	for (int i = 0; i< 4; i++)
	{
    
    
		stream.writeStartElement("EMP");
		stream.writeAttribute("Id", QString::number(i+1));
		stream.writeAttribute("Time", strTime[i]);

		stream.writeTextElement("name",str[i]);
		stream.writeTextElement("phone","188XXXXXXXXXX");
		stream.writeTextElement("age","30");
		stream.writeEndElement();
	}

	stream.writeEndElement();
	stream.writeEndDocument();
	file.close();
}

XML document effect:

<?xml version="1.0" encoding="UTF-8"?>
<DATA>
    <EMP Id="1" Time="20220101">
        <name>Amy</name>
        <phone>188XXXXXXXXXX</phone>
        <age>30</age>
    </EMP>
    <EMP Id="2" Time="20220815">
        <name>Linda</name>
        <phone>188XXXXXXXXXX</phone>
        <age>30</age>
    </EMP>
    <EMP Id="3" Time="20221212">
        <name>Joan</name>
        <phone>188XXXXXXXXXX</phone>
        <age>30</age>
    </EMP>
    <EMP Id="4" Time="20230115">
        <name>icy</name>
        <phone>188XXXXXXXXXX</phone>
        <age>30</age>
    </EMP>
</DATA>

QXmlStreamReader reads XMl documents:

Commonly used functions:

readNext(): Read the next token from the xml input stream.

name(): the name of the token, ie <name></name>

isStartElement(): Determine whether the currently read token is the start element, the start element is <>

isEndElement(): Determine whether the currently read token is the end element, the end element is </>

readElementText(): Read the text value corresponding to the current token, <>text value</>

atEnd(): Determine whether it is the end of the file

Code example:

void xmlRead()
{
    
    
	QString str;
	QFile file("./first.xml");
	if(!file.open(QFile::ReadOnly|QFile::Text))
	{
    
    
		qDebug() << "Failed to open file";  //文件打开失败
		return; 
	}

	QXmlStreamReader reader(&file);
	QXmlStreamReader::TokenType mtype = reader.readNext(); //读取下一个记号,并返回类型 

	if (QXmlStreamReader::StartDocument == mtype)
	{
    
    
		qDebug()<<"读取文件开始-"<<"版本号:"<<reader.documentVersion()<<"编码格式:"<<reader.documentEncoding();
	}
	
	while(!reader.atEnd())
	{
    
    
		if(reader.isStartElement())
		{
    
    
			QString STR = reader.name().toString();
			if(reader.name() == "EMP")
			{
    
    
				QXmlStreamAttributes attributes = reader.attributes(); //获取元素的属性

				if (attributes.hasAttribute("Id"))
				{
    
    
					qDebug() << attributes.value("Id");	//返回值是QStringRef,可以通过toString()转换成QString类型
				}
				if (attributes.hasAttribute("Time"))
				{
    
    
					qDebug() << attributes.value("Time");
				}
			}
			else if (reader.name() == "name")
			{
    
    
				str = reader.readElementText();
				qDebug() << str;
			}
			else if (reader.name() == "phone")
			{
    
    
				str = reader.readElementText();
				qDebug() << str;
			}
			else if(reader.name() == "age" )
			{
    
    
				str = reader.readElementText();
				qDebug() << str << endl;
			}
		}
		else if (reader.isEndElement())
		{
    
    
			if(reader.name() == "EMP")
			{
    
    
				qDebug()<<endl;
			}
		}
		mtype = reader.readNext();
	}

	file.close();
}

Read the effect, the console prints:

读取文件开始- 版本号: "1.0" 编码格式: "UTF-8"
"1"
"20220101"
"Amy"
"188XXXXXXXXXX"
"30"



"2"
"20220815"
"Linda"
"188XXXXXXXXXX"
"30"



"3"
"20221212"
"Joan"
"188XXXXXXXXXX"
"30"



"4"
"20230115"
"icy"
"188XXXXXXXXXX"
"30"



请按任意键继续. . .

Guess you like

Origin blog.csdn.net/yulong_abc/article/details/128694809