boost中提供了对配置文件读取的支持,它就是:property_tree。
basic_ptree 是property_tree的核心基础。其接口像std::list。可以执行很多基本的元素操作,比如使用begin()、end()等。
此外还加入了操作属性树的get()、get_child()、get_value()、data()等额外的操作。
basic_ptree有两个重要的内部定义self_type和value_type。self_type是basic_ptree模板实例化后自身的类型,它也是子节点的类型。value_type是节点的数据结构,它是一个std::pair,它含有属性名(first)和节点自身(second)。
通常不使用basic_ptree,而是使用预定义的typedef ptree、wptree、iptree、wiptree。前缀i表示忽略大小写,前缀w表示支持宽字符。
例如:
config.xml
[html] view plaincopyprint? 01.<?xml version="1.0" encoding="utf-8"?> 02.<con> 03. <id>1</id> 04. <name>fansy</name> 05. <urls> 06. <url>http://blog.csdn.net//fansongy</url> 07. <url>http://weibo.com//fansongy</url> 08. </urls> 09.</con>
我要读取它的数据:
01.#include <iostream> 02.#include <boost/property_tree/ptree.hpp> 03.#include <boost/property_tree/xml_parser.hpp> 04.#include <boost/typeof/typeof.hpp> 05.using namespace std; 06.using namespace boost::property_tree; 07.int main() 08.{ 09. ptree pt; 10. read_xml("conf.xml",pt); //读入一个xml文件 11. cout<<"ID is "<<pt.get<int>("con.id")<<endl; //读取节点中的信息 12. cout<<"Try Default"<<pt.get<int>("con.no_prop",100)<<endl; //如果取不到,则使用默认值 13. ptree child = pt.get_child("con"); //取一个子节点 14. cout<<"name is :"<<child.get<string>("name")<<endl; //对子节点操作,其实跟上面的操作一样 15. 16. child = pt.get_child("con.urls"); 17. for(BOOST_AUTO(pos,child.begin());pos != child.end();++pos) //boost中的auto 18. { 19. cout<<"\t"+pos->second.data()<<endl; 20. } 21. pt.put("con.name","Sword"); //更改某个键值 22. pt.add("con.urls.url",http://www.baidu.com); //增加某个键值 23. write_xml("conf.xml",pt); //写入XML 24. getchar(); 25. return 0; 26.}
01.运行的显示为: 02.ID is 1 03.Try Default100 04.name is :fansy 05. http://blog.csdn.net//fansongy 06. http://weibo.com//fansongy
config.xml为:
<?xml version="1.0" encoding="utf-8"?> <con> <id>1</id> <name>Sword</name> <urls> <url>http://blog.csdn.net//fansongy</url> <url>http://weibo.com//fansongy</url> <url>http://www.baidu.com</url> </urls> </con>
转载:点击打开链接