标签:blog http 使用 os io 文件 for ar
<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 };
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 file
16 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 }
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 }
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>
使用boost中的property_tree实现配置文件,布布扣,bubuko.com
标签:blog http 使用 os io 文件 for ar
原文地址:http://www.cnblogs.com/lidabo/p/3905827.html