加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用rapidxml读写xml文件

发布时间:2020-12-16 05:56:54 所属栏目:百科 来源:网络整理
导读: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(rapi

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),0);

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

	outfile << doc;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读