property_tree是专为配置文件而写,支持xml,ini和json格式文件
ini比较简单,适合简单的配置,通常可能需要保存数组,这时xml是个不错的选择。
使用property_tree也很简单,boost自带的帮助中有个5分钟指南
这里写一下使用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>
定义结构体如下:
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:需要包含以下文件
-
#include <boost/property_tree/ptree.hpp>
-
#include <boost/property_tree/xml_parser.hpp>
-
#include <boost/foreach.hpp>
-
#include <vector>
-
#include <string>
-
#include <exception>
-
#include <iostream>
阅读(1262) | 评论(0) | 转发(0) |