您的位置:首页 > 其它

使用rapidxml读写xml文件

2016-02-02 16:31 507 查看
1、rapidxml 写xml

rapidxml::xml_document<> doc;
rapidxml::xml_node<>* rot = doc.allocate_node(rapidxml::node_pi,doc.allocate_string("xml version='1.0' encoding='gb2312'"));
doc.append_node(rot);
rapidxml::xml_node<>* node =   doc.allocate_node(rapidxml::node_element,"config",NULL);
doc.append_node(node);

for(int i=0;i<5;i++)
{
rapidxml::xml_node<>* stu =   doc.allocate_node(rapidxml::node_element,"student",NULL);
node->append_node(stu);

char t[256];
sprintf(t, "%d", i);
std::string itag=t;

std::string strname="test_"+itag;
char* pname = doc.allocate_string(strname.c_str());

rapidxml::xml_attribute<>* pAttrType1=doc.allocate_attribute("name",pname);
stu->append_attribute(pAttrType1);

std::string strage="河北省小山村"+itag;
char* page= doc.allocate_string(strage.c_str());

pAttrType1=doc.allocate_attribute("adress",page);
stu->append_attribute(pAttrType1);
}
std::string text;
rapidxml::print(std::back_inserter(text), doc, 0);

std::ofstream out("config.xml");
out << doc;
效果:

遍历xml,修改指定属性的值

setlocale(LC_ALL, ""); // 解决中文路径问题(fstream)
rapidxml::file<> f("config.xml");
setlocale(LC_ALL, "C");
rapidxml::xml_document<> doc;

//doc.parse<0>(f.data());不包括版本号以及编码
doc.parse<rapidxml::parse_full>(f.data());

rapidxml::xml_node<>* pRoot = doc.first_node();
if(pRoot == NULL)
{
return;
}
pRoot = pRoot->next_sibling();//config节点

for(rapidxml::xml_node<>* pExeElem = pRoot->first_node(); pExeElem != NULL; pExeElem = pExeElem->next_sibling())
{
std::string szDstType;
rapidxml::xml_attribute<>* pAttrType = pExeElem->first_attribute("name");
if(pAttrType != NULL)
{
szDstType = pAttrType->value();
}
if(szDstType.compare("test_1") == 0)
{
rapidxml::xml_attribute<>* pAttrType1 = pExeElem->first_attribute("adress");
std::string strpath="浙江省";
char* pname = doc.allocate_string(strpath.c_str());
pAttrType1->value(pname);
}
}

std::string text ;
rapidxml::print(std::back_inserter(text), doc, 0);

setlocale(LC_ALL, ""); // 解决中文路径问题(fstream)=
std::ofstream outfile("config2.xml");
setlocale(LC_ALL, "C");

outfile << doc;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: