最近经常会遇到解析配置文件,而配置文件经常会用到xml。广泛的使用的xml解析器是tinyxml
- 简介
TinyXML是一个简单的小型C ++ XML解析器,可以轻松集成到其他程序中。他是一个开源免费的xml解析器。
网址:http://www.grinninglizard.com/tinyxml/
github:https://github.com/leethomason/tinyxml2
- 安装使用
下载:推荐使用github直接拉取代码 git clone https://github.com/leethomason/tinyxml2
大致浏览一下readme文件,了解一下基本用法
安装到自己的项目:只需要添加项目的.h文件和.cpp文件即可。
下面就可以开始写代码了;
首先我们写一个自己的xml。
<?xml version="1.0" encoding="utf-8"?>
<head>
<version value="8"/>
</head>
然后写上我们的xml读取cpp
#include "tinyxml2.h"
#include <iostream>
using namespace tinyxml2;
int main()
{
try
{
tinyxml2::XMLDocument doc;
doc.LoadFile("XMLFile.xml");
tinyxml2::XMLElement *root = doc.FirstChildElement("head");
if (root)
{
tinyxml2::XMLElement *p = root->FirstChildElement("version");
if (p)
{
int a = 0;
a = atoi(p->Attribute("value"));
printf_s("从xml中读取到a的值为:%d\n",a);
p->SetAttribute("value", 8);
a = atoi(p->Attribute("value"));
printf_s("保存到xml的value值为:%d\n", a);
doc.SaveFile("XMLFile.xml");
}
}
}
catch (const std::exception&)
{
printf_s("xml读取出错\n");
}
system("PAUSE");
return 0;
}
-
运行结果
-
被修改的xml
-
好了,最后贴出此项目的github:https://github.com/DengLangCode/TicppXml