Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7775527
  • 博文数量: 701
  • 博客积分: 2150
  • 博客等级: 上尉
  • 技术积分: 13233
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-29 16:28
个人简介

天行健,君子以自强不息!

文章分类

全部博文(701)

文章存档

2019年(2)

2018年(12)

2017年(76)

2016年(120)

2015年(178)

2014年(129)

2013年(123)

2012年(61)

分类: C/C++

2015-12-17 14:19:27

property_tree是专为配置文件而写,支持xml,ini和json格式文件

ini比较简单,适合简单的配置,通常可能需要保存数组,这时xml是个不错的选择。

使用property_tree也很简单,boost自带的帮助中有个5分钟指南

 
这里写一下使用xml来保存多维数组,在有些情况下一维数组并不能满足要求。
举个简单的例子吧:
xml格式如下:

  1. <debug>
  2.   <total>3</total>
  3.   <persons>
  4.     <person>
  5.     <age>23</age>
  6.     <name>hugo</name>
  7.   </person>
  8.   <person>
  9.     <age>23</age>
  10.      <name>mayer</name>
  11.   </person>
  12.   <person>
  13.     <age>30</age>
  14.     <name>boy</name>
  15.   </person>
  16.   </persons>
  17. </debug>


定义结构体如下:
struct person
{
 int age;
 std::string name;
};


struct debug_persons
{
 int itsTotalNumber;
 std::vector itsPersons;
 void load(const std::string& filename);
 void save(const std::string& filename);
};

2个载入和保存的函数:
void debug_persons::save( const std::string& filename )
{
 using boost::property_tree::ptree;
 ptree pt;


 pt.put("debug.total", itsTotalNumber);


 BOOST_FOREACH(const person& p,itsPersons)
 {
  ptree child;
  child.put("age",p.age);
  child.put("name",p.name);
  pt.add_child("debug.persons.person",child);
 }
 // Write property tree to XML file
 write_xml(filename, pt);

}


void debug_persons::load( const std::string& filename )
{
 using boost::property_tree::ptree;
 ptree pt;


 read_xml(filename, pt);
 itsTotalNumber = pt.get("debug.total");


 BOOST_FOREACH(ptree::value_type &v, pt.get_child("debug.persons"))
 { 
  //m_modules.insert(v.second.data());
  person p;
  p.age = v.second.get("age");
  p.name = v.second.get("name");
  itsPersons.push_back(p);
 }
}


main中的代码
int _tmain(int argc, _TCHAR* argv[])
{
 
 try
 {
    debug_persons dp;
    dp.load("debug_persons.xml");
    std::cout<     person p;
    p.age = 100;
    p.name = "old man";
    dp.itsPersons.push_back(p);
    dp.save("new.xml");
    std::cout << "Success\n";
 }
 catch (std::exception &e)
 {
  std::cout << "Error: " << e.what() << "\n";
 }
 return 0;
}




这里为了调试输出增加了以下代码:
std::ostream& operator<<(std::ostream& o,const debug_persons& dp)
{
   o << "totoal:" << dp.itsTotalNumber << "\n";
   o << "persons\n";
   BOOST_FOREACH(const person& p,dp.itsPersons)
   {
      o << "\tperson: Age:" << p.age << " Nmae:" << p.name << "\n";
   }
 return o;
}



ps:需要包含以下文件

  1. #include <boost/property_tree/ptree.hpp>
  2. #include <boost/property_tree/xml_parser.hpp>
  3. #include <boost/foreach.hpp>
  4. #include <vector>
  5. #include <string>
  6. #include <exception>
  7. #include <iostream>



阅读(1217) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~