VC++访问XML文件,使用pugixml
首先包含pugixml头文件,且添加相应的DLL文件,附资源。
#include “pugixml.hpp”
1.向XML写入内容
1. //创建xml_document;
pugi::xml_document Mydocument;
2. //插入declaration;
pugi::xml_node decl = Mydocument.append_child(pugi::node_declaration);
decl.append_attribute("version")="2.0";
3. //并列插入Message结点;
pugi::xml_node Message = Mydocument.append_child("Message");
4. //在Message结点下面插入date结点;
pugi::xml_node date = Message.append_child("date");
date.append_child(pugi::node_pcdata).set_value("2019/10/14");//在结点间插入文本信息
5. //在message下面插入Params结点;
pugi::xml_node Params = Message.append_child("Params");
6. //在Params下面插入param结点;
pugi::xml_node Param1 = Params.append_child("Param");
Param1.append_attribute("name")="proname";//append_attribute表示插入属性;
Param1.append_attribute("type")= "string";
Param1.append_attribute("value")= "P";
pugi::xml_node name1 = Param1.append_child("name1");
name1.append_child(pugi::node_pcdata).set_value("shan");//node_pcdata表示写入xml中的为文本信息;
7. //保存文件
Mydocument.save_file("自定义路径+\\Message.xml");
结果:
2. 读取XML文件中的内容
示例xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<!-- 输入参数配置 -->
<form ip="10.2.134.243" port="80" action="sisserver.php">
<input name="data_type" value="POI" />
<input name="query_type" value="TQUERY" />
<input name="category" value="67" />
</form>
</root>
1) 加载所要读取的XML文件
std::string strFile ="自定义路径+ \\params.xml";
pugi::xml_document doc;
//加载xml文件;
if (!doc.load_file(strFile.c_str()))
{return 0;}
2) 获取XML文件中root结点中的form结点
pugi::xml_node form = doc.child("root").child("form");
std::string ip = form.attribute("ip").value();//获取from结点的ip属性值;
std::string port = form.attribute("port").value();//获取from结点的port属性值;
printf("IP为:%s,端口为:%s \n",ip.c_str(), port.c_str());
3) 获取XML文件中form结点中的所有input结点
char cBuf[1024];//声明一个字符数组,相当于一个缓存buffer;
int i,j =0;//标识缓存中数据的位置;
memset(cBuf,0x00,sizeof(cBuf));//初始化缓存;
//遍历form结点下的所有input结点;
for (pugi::xml_node input =form.first_child();input;input = input.next_sibling())
{
//获取input结点中变量value的值;
std::string strValue = input.attribute("value").value();
//如果input中对应的变量value的值不为空,则将其输出;
if (!strValue.empty())
{
std::string strName = input.attribute("name").value();
i =sprintf(cBuf+j, " %s = %s \n", strName.c_str(), strValue.c_str());
j = j+i;
}
}
//将缓存中的数据输出;
printf( "Output: \n%s\ncharacter count = %d\n", cBuf, j );