使用rapidxml读写xml文件

本文介绍了如何使用rapidxml库进行XML文件的读写操作,特别是详细阐述了如何遍历XML文档并修改特定属性值的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值