c++中读写xml文件分为两种:

1.方法一:使用tinyxml库来操作xml文件

2.方法二:使用QT中的QDomDoucment来对xml进行操作#include<QDomDoucment>

方法一:首先你可以在github上下载最新的tinyxml库(这里对下载配置tinyxml库就不多说了)

tinyxml写文件:

#include <tinyxml.h>
#include <iostream>

using namespace std;

int main()
{
    string filename = "text.xml";
    //创建xml文档
    TiXmlDoucment *doc = new TiXmlDoucment();
    
    //写入xml文件的头部
    TiXmlDeclartion *head = new TiXmlDeclartion("1.0","UTF-8","");
    doc->LinkEndChild(head);
    
    //创建根节点
    TiXmlElement *root = new TiXmlElement("serve");
    doc->LinkEndChild(root);
    
    TiXmlElement *rootChild = new TiXmlElement("socket");
    root->LinkEndChild(rootChild);
    rootChild->setAttribute("id" "1");
    
    TiXmlElement *ip = new TiXmlElement("ip");
    rootChid->LinkEndChild(ip);

    TiXmlElement *port = new TiXmlElement("port");
    rootChild->LinkEndChild(port);

    TiXmlText *ipText = new TiXmlText("192.0.0.1");
    ip->LinkEndChild(ipText);

    TiXmlText *portText = new TiXmlText("8080");
    port->LinkEndChild(portText);

    doc->saveFile(filename);
    return 0;
}

tinyxml读文件

#include "tinyxml.h"
#include <iostream>

using namespace std;

int main()
{
    string filename = "text.xml";
    //创建xml文件对象
    TiXmlDoucment *doc = new TiXmlDoucment(filename.c_str());
    
    //判断文件是否正确
    if(!doc->Loadfile())
    {
        cout << "文件错误!!!" << endl;
        return 0;
    }    

    //提取出root节点
    TiXmlElement * root = doc->rootElement();
    cout << root->value() << endl;

    //去出根节点的孩子节点
    TiXmlElement * firstChild = root->FirstChildElement();
    
    //获取属性值
    TiXmlAttribute * attr = firstChild->FirstAttribute();
    cout << attr->value() << endl;

    TiXmlElement * ip = firstChild->FirstChildElement();
    TiXmlElement * port = firstChild->NextSiblingElement();

    cout << ip->firstChild()->value() << endl;
    cout << port->FirstChild()->value() << endl;

    return 0;
}

方法二:敬请期待

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐