使用rapidxml读写xml文件

前端之家收集整理的这篇文章主要介绍了使用rapidxml读写xml文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、rapidxml 写xml

  1. rapidxml::xml_document<> doc;
  2. rapidxml::xml_node<>* rot = doc.allocate_node(rapidxml::node_pi,doc.allocate_string("xml version='1.0' encoding='gb2312'"));
  3. doc.append_node(rot);
  4. rapidxml::xml_node<>* node = doc.allocate_node(rapidxml::node_element,"config",NULL);
  5. doc.append_node(node);
  6.  
  7. for(int i=0;i<5;i++)
  8. {
  9. rapidxml::xml_node<>* stu = doc.allocate_node(rapidxml::node_element,"student",NULL);
  10. node->append_node(stu);
  11.  
  12. char t[256];
  13. sprintf(t,"%d",i);
  14. std::string itag=t;
  15.  
  16. std::string strname="test_"+itag;
  17. char* pname = doc.allocate_string(strname.c_str());
  18.  
  19. rapidxml::xml_attribute<>* pAttrType1=doc.allocate_attribute("name",pname);
  20. stu->append_attribute(pAttrType1);
  21.  
  22. std::string strage="河北省小山村"+itag;
  23. char* page= doc.allocate_string(strage.c_str());
  24.  
  25. pAttrType1=doc.allocate_attribute("adress",page);
  26. stu->append_attribute(pAttrType1);
  27. }
  28. std::string text;
  29. rapidxml::print(std::back_inserter(text),doc,0);
  30.  
  31. std::ofstream out("config.xml");
  32. out << doc;
效果

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

  1. setlocale(LC_ALL,""); // 解决中文路径问题(fstream)
  2. rapidxml::file<> f("config.xml");
  3. setlocale(LC_ALL,"C");
  4. rapidxml::xml_document<> doc;
  5.  
  6. //doc.parse<0>(f.data());不包括版本号以及编码
  7. doc.parse<rapidxml::parse_full>(f.data());
  8.  
  9. rapidxml::xml_node<>* pRoot = doc.first_node();
  10. if(pRoot == NULL)
  11. {
  12. return;
  13. }
  14. pRoot = pRoot->next_sibling();//config节点
  15.  
  16. for(rapidxml::xml_node<>* pExeElem = pRoot->first_node(); pExeElem != NULL; pExeElem = pExeElem->next_sibling())
  17. {
  18. std::string szDstType;
  19. rapidxml::xml_attribute<>* pAttrType = pExeElem->first_attribute("name");
  20. if(pAttrType != NULL)
  21. {
  22. szDstType = pAttrType->value();
  23. }
  24. if(szDstType.compare("test_1") == 0)
  25. {
  26. rapidxml::xml_attribute<>* pAttrType1 = pExeElem->first_attribute("adress");
  27. std::string strpath="浙江省";
  28. char* pname = doc.allocate_string(strpath.c_str());
  29. pAttrType1->value(pname);
  30. }
  31. }
  32.  
  33. std::string text ;
  34. rapidxml::print(std::back_inserter(text),0);
  35.  
  36. setlocale(LC_ALL,""); // 解决中文路径问题(fstream)=
  37. std::ofstream outfile("config2.xml");
  38. setlocale(LC_ALL,"C");
  39.  
  40. outfile << doc;

猜你在找的XML相关文章