property_tree是专为配置文件而写,支持xml,ini和json格式文件
ini比较简单,适合简单的配置,通常可能需要保存数组,这时xml是个不错的选择。
使用property_tree也很简单,boost自带的帮助中有个5分钟指南
http://www.boost.org/doc/libs/1_46_1/doc/html/boost_propertytree/tutorial.html
这里写一下使用xml来保存多维数组,在有些情况下一维数组并不能满足要求。
举个简单的例子吧:
xml格式如下:
<debug> <total>3</total> <persons> <person> <age>23</age> <name>hugo</name> </person> <person> <age>23</age> <name>mayer</name> </person> <person> <age>30</age> <name>boy</name> </person> </persons></debug>
定义结构体如下:
1 struct person 2 { 3 int age; 4 std::string name; 5 }; 6 7 struct debug_persons 8 { 9 int itsTotalNumber;10 std::vector<person> itsPersons;11 void load(const std::string& filename);12 void save(const std::string& filename);13 };
2个载入和保存的函数:
1 void debug_persons::save( const std::string& filename ) 2 { 3 using boost::property_tree::ptree; 4 ptree pt; 5 6 pt.put("debug.total", itsTotalNumber); 7 8 BOOST_FOREACH(const person& p,itsPersons) 9 {10 ptree child;11 child.put("age",p.age);12 child.put("name",p.name);13 pt.add_child("debug.persons.person",child);14 }15 // Write property tree to XML file16 write_xml(filename, pt);17 18 }19 20 void debug_persons::load( const std::string& filename )21 {22 using boost::property_tree::ptree;23 ptree pt;24 25 read_xml(filename, pt);26 itsTotalNumber = pt.get<int>("debug.total");27 28 BOOST_FOREACH(ptree::value_type &v, pt.get_child("debug.persons"))29 { 30 //m_modules.insert(v.second.data());31 person p;32 p.age = v.second.get<int>("age");33 p.name = v.second.get<std::string>("name");34 itsPersons.push_back(p);35 }36 }
main中的代码
1 int _tmain(int argc, _TCHAR* argv[]) 2 { 3 4 try 5 { 6 debug_persons dp; 7 dp.load("debug_persons.xml"); 8 std::cout<<dp<<std::endl; 9 person p;10 p.age = 100;11 p.name = "old man";12 dp.itsPersons.push_back(p);13 dp.save("new.xml");14 std::cout << "Success\n";15 }16 catch (std::exception &e)17 {18 std::cout << "Error: " << e.what() << "\n";19 }20 return 0;21 }
这里为了调试输出增加了以下代码:
1 std::ostream& operator<<(std::ostream& o,const debug_persons& dp) 2 { 3 o << "totoal:" << dp.itsTotalNumber << "\n"; 4 o << "persons\n"; 5 BOOST_FOREACH(const person& p,dp.itsPersons) 6 { 7 o << "\tperson: Age:" << p.age << " Nmae:" << p.name << "\n"; 8 } 9 return o;10 }
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>
时间: 2024-09-15 05:11:14