C++, Qt read and write xml files respectively

XML syntax

The first line is the XML document declaration, and the representation inside <> is an element. The basic syntax is as follows. It is common for C++ to use the tiny library to read and write, and Qt uses its own library to read and write;

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<根元素>
   <元素 属性名="属性值" 属性名="属性值">Text</元素>
   <元素 属性名="属性值" 属性名="属性值">
       <子元素>Text</子元素>
   </元素>
</根元素>

C++ uses tinyxml to read and write xml

First download the tinyxml library from the website,
and load the 6 files into your own project:
insert image description here

Write XML:

Create a new file and write:

#include "include/tinyxml.h"

string strPath = "E:/test.xml";
TiXmlDocument *writeDoc = new TiXmlDocument; //xml文档指针
//文档格式声明
TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "UTF-8", "yes");
writeDoc->LinkEndChild(decl); //写入文档
//TiXmlElement父类的析构函数内自带delete,所以不用自己释放
TiXmlElement *RootElement = new TiXmlElement("Camera");//根元素
RootElement->SetAttribute("num", "3"); //属性
writeDoc->LinkEndChild(RootElement);
TiXmlElement *StuElement = new TiXmlElement("Exposure");//Stu
//设置属性
StuElement->SetAttribute("time", "A");
StuElement->SetAttribute("deley", "30");
RootElement->LinkEndChild(StuElement);//父节点写入文档
//子元素
TiXmlElement *sonElement1 = new TiXmlElement("max");
StuElement->LinkEndChild(sonElement1);
TiXmlText *maxContent = new TiXmlText("1000");
sonElement1->LinkEndChild(maxContent);

TiXmlElement *sonElement2 = new TiXmlElement("min");
StuElement->LinkEndChild(sonElement2);
TiXmlText *minContent = new TiXmlText("80");
sonElement2->LinkEndChild(minContent);


writeDoc->SaveFile(strPath.c_str());
delete writeDoc;

The final generated xml file is:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Camera num="3">
    <Exposure time="A" deley="30">
        <max>1000</max>
        <min>80</min>
    </Exposure>
</Camera>

So, use the classes in the tinyxml library to read and write the root element, text and attributes. Four classes and three functions are mainly used here:

<TiXmlDeclaration>
<TiXmlElement>
     <TiXmlElement>
        <TiXmlElement>TiXmlText</TiXmlElement>
     </TiXmlElement>
</TiXmlElement>

Four classes:
TiXmlDocument: defines some basic operations of xml files, including file flow;
TiXmlDeclaration: used for the first line of xml files, defines the declaration operations of xml files;
TiXmlElement: regardless of root element, element and child element, all use This class;
TiXmlText: used for the operation of text in the element;
three functions:
LinkEndChild: Embed the child element in the parent element, and add text to the element
SetAttribute: Set the attribute name and attribute value in
the element SaveFile: Used to save the xml file; if the xml file does not exist, one will be created automatically;

Read XML:

TiXmlDocument mydoc("E:/test.xml");
if(!mydoc.LoadFile())
{
    
    
   return;
}
TiXmlElement *RootElement = mydoc.RootElement();   //获取根元素
//遍历根元素下的元素
for(TiXmlElement *StuElement = RootElement->FirstChildElement();//第一个子元素
		StuElement != NULL;
		StuElement = StuElement->NextSiblingElement())//下一个兄弟元素
{
    
    
        //先找到Exposure元素
		if (0 == strcmp("Exposure", StuElement->Value()))
		{
    
    
			//遍历Exposure元素下的子元素
			for (TiXmlElement *sonElement = StuElement->FirstChildElement();
			     sonElement != NULL;
				 sonElement = sonElement->NextSiblingElement())
			{
    
    
				//找到max元素,并输出元素内的text
				if (0 == strcmp("max", sonElement->Value()))
				{
    
    
					string str = sonElement->GetText();
					cout << str.c_str() << endl;
				}
			}
		}
}

insert image description here

Qt read and write xml

Write XML:

//头文件
#include <QDomDocument>
QString fileName = "E:/test.xml";
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly|QIODevice::Truncate))
  return;
//定义xml文件
QDomDocument doc;
//定义格式头
QDomProcessingInstruction ins = doc.createProcessingInstruction("xml","version = \'1.0\' encoding = \'utf-8\'");
//追加元素
doc.appendChild(ins);
//根节点元素
QDomElement root = doc.createElement("Camera");
doc.appendChild(root);
//在根节点的基础上增加一个子节点
QDomElement sonEmt = doc.createElement("Exposure");
//创建元素的属性名
QDomAttr sonAttr = doc.createAttribute("time");
//创建元素的属性值
sonAttr.setNodeValue("100");
//节点和属性关联
sonEmt.setAttributeNode(sonAttr);
root.appendChild(sonEmt);
//在根节点的基础上增加一个子节点,并设置子节点的text
QDomElement sonOneEmt = doc.createElement("max");
QDomText sonOneText = doc.createTextNode("1000");
sonOneEmt.appendChild(sonOneText);
sonEmt.appendChild(sonOneEmt);

QDomElement sonTwoEmt = doc.createElement("min");
QDomText sonTwoText = doc.createTextNode("80");
sonTwoEmt.appendChild(sonTwoText);
sonEmt.appendChild(sonTwoEmt);

//写入文件
QTextStream stream(&file);
doc.save(stream,4);//4缩进

The corresponding classes here are:

<QDomProcessingInstruction>
<QDomElement>
   <QDomElement>QDomText</QDomElement>
   <QDomElement QDomAttr>
   </QDomElement>
</QDomElement>

Read XML:

#include <QXmlStreamReader>

QDomDocument doc;
QString fileName = "E:/test.xml";
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly|QIODevice::Truncate))
{
    
    
    return;
}
else
{
    
    
    //将文件内容读到doc中
    if(!doc.setContent(&file))
        file.close();
    //返回根元素
    QDomElement root = doc.documentElement();
    //返回根元素的名称
    QDomNode n = root.firstChild();
    while(!n.isNull())
    {
    
    
       if(n.isElement())
       {
    
    
         QDomElement e = n.toElement();
         QString strXML = qPrintable(e.tagName());
         //判断第一个节点
         if("Exposure" == strXML)
         {
    
    
             //遍历寻找Exposure元素下的子元素,并找到其text
             QDomNodeList list = e.childNodes();
             for(int i=0;i<list.count();i++)
             {
    
    
                QDomNode node = list.at(i);
                strXML = qPrintable(node.toElement().tagName());
                //判断第二个元素
                if(node.isElement() && "max"== strXML)
                  QString textStr = qPrintable(node.toElement().text());//读取子元素内的text
             }
         }
       }
    }
}

The effect of interface reading is:
insert image description here

Guess you like

Origin blog.csdn.net/qq_43376782/article/details/128564917