使用pugixml库需要三个文件:pugiconfig.h/pugixml.h/pugixml.cpp,可直接从gugixml官网下载,将其加入工程,使用处包含头文件pugiconfig.h/pugixml.h即可。
#include <iostream>
#include "pugiconfig.hpp"
#include "pugixml.hpp"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
using namespace pugi;
//读节点属性
bool ReadXml(const char *xmlfile)
{
xml_document doc;
if(doc.load_file(xmlfile))
{
cout<<"....."<<endl;
return false;
}
//input属性值
xml_node form=doc.child("root").child("form");//得到根节点下的子节点
string ip=form.attribute("ip").value();//得到属性值
string port=form.attribute("port").value();//得到属性值
string action=form.attribute("action").value();//得到属性值
cout<<ip.data()<<endl;
cout<<port.data()<<endl;
cout<<action.data()<<endl;
return true;
}
//遍历根节点下的字节点
bool TravelXml(const char *xmlfile)
{
xml_document doc;
if(doc.load_file(xmlfile))
{
cout<<"load error"<<endl;
return false;
}
xml_node form=doc.child("root").child("form");
for(xml_node input=form.first_child();input;input=input.next_sibling())
{
string strname=input.attribute("name").value();
cout<<"name="<<strname<<endl;
if(!strname.empty())
{
string strvalue=input.attribute("value").value();
cout<<"value="<<strvalue<<endl;
}
}
return true;
}
//增加节点
bool AppendXml(const char *xmlfile)
{
xml_document doc;
if(!doc.load_file(xmlfile))
{
cout<<"load error"<<endl;
return false;
}
xml_node root=doc.child("root");
root.append_child("wei");
doc.save_file(xmlfile);
return true;
}
//删除节点
bool RemoveXml(const char *xmlfile)
{
xml_document doc;
if(!doc.load_file(xmlfile))
{
cout<<"load error"<<endl;
return false;
}
xml_node root=doc.child("root");
root.remove_child("wei");
doc.save_file(xmlfile);
return true;
}
int main(void)
{
ReadXml("./example1.xml");
// TravelXml("./example1.xml");
// AppendXml("./example1.xml");
// RemoveXml("./example1.xml");
return 0;
}