boost的property_tree组件

boost的property_tree组件


目录(?)[+]

1.1 缘起

stl中对线性表有充分的实现,无论是vector还是list都是典型的线性表,即便是set和map,尽管实现上采用了诸如红黑树之类的树形结构,但那仅仅是为了快速检索的需要,从语义上来说它们依旧是线性表,无法表达目录树这种树形结构。boost中的property_tree可以看做是对树形结构实现的补充,我们大可把它扩展应用到各种需要树形结构的地方。

当我们拥有了一个树性结构以后,那么也就同时拥有了树形结构中的每个节点的访问权,很自然的,我们希望每个节点都可以方便的检索(类似于输入一个文件路径就快速的定位到文件),同时我们也希望能在节点上存储点什么以支持各种实际的应用。这里可以和MFC的树形控件CTreeCtrl做一下类比,MFC中的CTreeCtrl不支持类似于路径的检索,好在CTreeCtrl的节点中有一个字符串类型的名称,使得我们可以通过字符串和不断的GetChildItem,GetNextItem自己去检索定位;同时它的每个节点都可以存储一个int数据,并通过方法SetItemData和GetItemData进行读取,然后再通过这个int数据再关联到那些比int更复杂的数据结构。这种通过int数据二次关联的实现是能够工作的,只是有些繁琐。而在boost的泛型世界里,再如此硬编码一个类型肯定会被人笑话的。标准的做法是为树形结构的每个节点关联一个模板Key类型的索引数据和一个Data类型的存储数据,至于Key和Data类型是什么,爱是谁是谁。这个被关联的Data类型的数据就是节点的属性(property)。说了这么多,我们终于可以解开property_tree的真面目了:

[cpp]  view plain  copy
  1. template<class Key, class Data, class KeyCompare>  
  2. class basic_ptree  
  3. {  
  4.     typedef basic_ptree<Key, Data, KeyCompare> self_type;  
  5.   
  6. public:  
  7.     // Basic types  
  8.     typedef Key                                  key_type;  
  9.     typedef Data                                 data_type;  
  10.     typedef KeyCompare                           key_compare;  
  11.   
  12.     // Container view types  
  13.     typedef std::pair<const Key, self_type>      value_type;  
  14.     typedef std::size_t                          size_type;  
  15.       
  16. private:  
  17.     // Hold the data of this node  
  18.     data_type m_data;  
  19.     // Hold the children - this is a void* because we can't complete the  
  20.     // container type within the class.  
  21.     void* m_children;  
  22. };  

其中的m_children又到底是什么类型呢?需要看下面的实现代码:

[cpp]  view plain  copy
 
  1. template<class K, class D, class C> inline  
  2. basic_ptree<K, D, C>::basic_ptree()  
  3.     : m_children(new typename subs::base_container)  
  4. {  
  5. }  
  6.   
  7. template <class K, class D, class C>  
  8. struct basic_ptree<K, D, C>::subs  
  9. {  
  10.     struct by_name {};  
  11.     // The actual child container.  
  12.     typedef multi_index_container<value_type,  
  13.         multi_index::indexed_by<  
  14.             multi_index::sequenced<>,  
  15.             multi_index::ordered_non_unique<multi_index::tag<by_name>,  
  16.                 multi_index::member<value_type, const key_type,  
  17.                                     &value_type::first>,  
  18.                 key_compare  
  19.             >  
  20.         >  
  21.     > base_container;    
  22. };  

multi_index也是boost中的一个组件,作用是为一个数据结构提供多种方式的索引,我们先不纠结于multi_index的细节,可以把它简化为list<value_type>,而value_type又是一个std::pair<const Key, self_type>。好了,整个树形的数据结构就串起来了,每个节点都保存一个data_type m_data,即一个Data类型的属性值,同时还保存一个list<value_type>,即以Key标识的所有子节点列表。

1.2 遍历

了解了property_tree的数据结构,树的遍历就很简单了。

首先,我们可以通过data方法得到节点上的属性值:

[cpp]  view plain  copy
 
  1. template<class K, class D, class C> inline  
  2. typename basic_ptree<K, D, C>::data_type &  
  3.     basic_ptree<K, D, C>::data()  
  4. {  
  5.     return m_data;  
  6. }  

其次,我们可以构造所有子节点的迭代器:

[cpp]  view plain  copy
 
  1. template <class K, class D, class C>  
  2. class basic_ptree<K, D, C>::iterator : public boost::iterator_adaptor<  
  3.     iterator, typename subs::base_container::iterator, value_type>  
  4. {  
  5.     friend class boost::iterator_core_access;  
  6.     typedef boost::iterator_adaptor<  
  7.         iterator, typename subs::base_container::iterator, value_type>  
  8.         baset;  
  9. public:  
  10.     typedef typename baset::reference reference;  
  11.     iterator() {}  
  12.     explicit iterator(typename iterator::base_type b)  
  13.         : iterator::iterator_adaptor_(b)  
  14.     {}  
  15.     reference dereference() const  
  16.     {  
  17.         // multi_index doesn't allow modification of its values, because  
  18.         // indexes could sort by anything, and modification screws that up.  
  19.         // However, we only sort by the key, and it's protected against  
  20.         // modification in the value_type, so this const_cast is safe.  
  21.         return const_cast<reference>(*this->base_reference());  
  22.     }  
  23. };  

基本上直接封装内部数据结构的迭代器就可以了。剩下的就是stl的迭代器的标准用法了。

现在,我们可以直接写出property_tree的遍历函数了,这里采用递归处理,以树形结构的打印为例,同时为了打印的方便,我们采用ptree:

[cpp]  view plain  copy
 
  1. //typedef basic_ptree<std::string, std::string> ptree;  
  2. void print(ostream& os, const ptree& pt, int tab)  
  3. {  
  4.     tab += 2;  
  5.     for (ptree::const_iterator iter = pt.begin(); iter != pt.end(); ++iter)  
  6.     {  
  7.         os << string(tab, ' ');  
  8.         os << "{" << iter->first << "}" << "[" << iter->second.data() << "]\n";  
  9.         print(os, iter->second, tab);  
  10.     }  
  11. }  

这里处理了tab的缩进,为什么一上来就+2?因为最外层的根节点其实是文档本身,而我们一般会跳过它。

1.3 Xml文件的读取

从property_tree的实现代码可以看到,其内部的xml解析采用了rapidxml,明晃晃的rapidxml.hpp是那么的显眼。这个号称是执行最快的xml解析的实现,既然要快,就不可能像xerces那样的庞大臃肿,步履蹒跚,当然也不可能象后者一样的面面俱到。(私下以为,如果property_tree敢用xerces,它也不可能被boost通过,呵呵)。

实现细节rapidxml被很好地封装起来,以保证未来实现部分的可替换性。对外直接给了read_xml和write_xml两个方法处理xml文件的读写,这里先看看read_xml方法:

[cpp]  view plain  copy
 
  1. template<class Ptree>  
  2. void read_xml(const std::string &filename,  
  3.               Ptree &pt,  
  4.               int flags = 0,  
  5.               const std::locale &loc = std::locale())  
  6. {  
  7.     BOOST_ASSERT(validate_flags(flags));  
  8.     std::basic_ifstream<typename Ptree::key_type::value_type>  
  9.         stream(filename.c_str());  
  10.     if (!stream)  
  11.         BOOST_PROPERTY_TREE_THROW(xml_parser_error(  
  12.             "cannot open file", filename, 0));  
  13.     stream.imbue(loc);  
  14.     read_xml_internal(stream, pt, flags, filename);  
  15. }  

好了,是时候写出property_tree读取xml的示例代码了:

[cpp]  view plain  copy
 
  1. void read_xml_demo()  
  2. {  
  3.     try  
  4.     {  
  5.         ptree doc;    
  6.         read_xml("config/config.xml", doc, xml_parser::trim_whitespace);  
  7.   
  8.         print(cout, doc, -2);  
  9.     }  
  10.     catch (xml_parser_error& e)  
  11.     {  
  12.         cout << e.what() << endl;  
  13.     }  
  14.     catch (std::exception& e)  
  15.     {  
  16.         cout << e.what() << endl;  
  17.     }  
  18. }  

代码非常简单,不解释了。这里示例的config.xml是下面的内容:

[html]  view plain  copy
 
  1. <?xml version="1.0" encoding="GB2312"?>  
  2. <config>  
  3.     <main title="windows" icon="main.ico">  
  4.     <!-- Main Fisrt Comment -->  
  5.     <!-- Main Second Comment -->  
  6.     </main>  
  7.     <paths name="init">  
  8.         <!-- Paths Comment -->  
  9.         <path level="1">a.ini</path>  
  10.         <path level="2">b.ini</path>  
  11.         <path level="3">c.ini</path>  
  12.     </paths>  
  13.     <links key="<>">  
  14.         <!-- Links Comment -->  
  15.         <link level="1">www.sina.com</link>  
  16.         <link level="2">www.sohu.com</link>  
  17.         <link level="3">www.163.com</link>  
  18.     </links>  
  19. </config>  

但是你能想到会打印出什么东西吗?这里其实有一个非常严重的问题:数据结构的不对等。

我们知道,xml本身结构是比较复杂的,节点的类型有:

[cpp]  view plain  copy
 
  1. enum node_type  
  2. {  
  3.     node_document,      //!< A document node. Name and value are empty.  
  4.     node_element,       //!< An element node. Name contains element name. Value contains text of first data node.  
  5.     node_data,          //!< A data node. Name is empty. Value contains data text.  
  6.     node_cdata,         //!< A CDATA node. Name is empty. Value contains data text.  
  7.     node_comment,       //!< A comment node. Name is empty. Value contains comment text.  
  8.     node_declaration,   //!< A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes.  
  9.     node_doctype,       //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text.  
  10.     node_pi             //!< A PI node. Name contains target. Value contains instructions.  
  11. };  
(摘自rapidxml.hpp。)
每个元素下还有一组属性和一个可选的text。
但是我们知道property_tree的数据结构是比较简单的,并不能支持xml这样的复杂结构。这个问题我估计也是让property_tree的作者很纠结的问题,被逼无奈之下,他采用了一个能工作但很难看的解决方案:字符串的私有协议。简单的说协议有两条:

  • 字符串”<xmlattr>” 表示该节点是xml属性
  • 字符串”<xmlcomment>” 表示该节点是xml注释
这样,当我们看到下面的输出结果就不会感到惊讶了:
[plain]  view plain  copy
 
  1. {config}[]  
  2.   {main}[]  
  3.     {<xmlattr>}[]  
  4.       {title}[windows]  
  5.       {icon}[main.ico]  
  6.     {<xmlcomment>}[ Main Fisrt Comment ]  
  7.     {<xmlcomment>}[ Main Second Comment ]  
  8.   {paths}[]  
  9.     {<xmlattr>}[]  
  10.       {name}[init]  
  11.     {<xmlcomment>}[ Paths Comment ]  
  12.     {path}[a.ini]  
  13.       {<xmlattr>}[]  
  14.         {level}[1]  
  15.     {path}[b.ini]  
  16.       {<xmlattr>}[]  
  17.         {level}[2]  
  18.     {path}[c.ini]  
  19.       {<xmlattr>}[]  
  20.         {level}[3]  
  21.   {links}[]  
  22.     {<xmlattr>}[]  
  23.       {key}[<>]  
  24.     {<xmlcomment>}[ Links Comment ]  
  25.     {link}[www.sina.com]  
  26.       {<xmlattr>}[]  
  27.         {level}[1]  
  28.     {link}[www.sohu.com]  
  29.       {<xmlattr>}[]  
  30.         {level}[2]  
  31.     {link}[www.163.com]  
  32.       {<xmlattr>}[]  
  33.         {level}[3]  

1.4 其它文件格式的读取

我在文章的开头就说过了property_tree是为树形结构而生的,而不仅仅只为xml而生的,因此property_tree还支持json、info、ini几种文件格式。了解了xml文件的读取后,这几种文件格式的读取也就比较简单了。

读取这三种文件的示例代码如下:

[cpp]  view plain  copy
 
  1. void read_json_demo()  
  2. {  
  3.     try  
  4.     {  
  5.         ptree doc;    
  6.         read_json("config/config.json", doc);  
  7.   
  8.         print(cout, doc, -2);  
  9.     }  
  10.     catch (json_parser_error& e)  
  11.     {  
  12.         cout << e.what() << endl;  
  13.     }  
  14.     catch (std::exception& e)  
  15.     {  
  16.         cout << e.what() << endl;  
  17.     }  
  18. };  
  19.   
  20. void read_ini_demo()  
  21. {  
  22.     try  
  23.     {  
  24.         ptree doc;    
  25.         read_ini("config/config.ini", doc);  
  26.   
  27.         print(cout, doc, -2);  
  28.     }  
  29.     catch (json_parser_error& e)  
  30.     {  
  31.         cout << e.what() << endl;  
  32.     }  
  33.     catch (std::exception& e)  
  34.     {  
  35.         cout << e.what() << endl;  
  36.     }  
  37. };  
  38.   
  39. void read_info_demo()  
  40. {  
  41.     try  
  42.     {  
  43.         ptree doc;    
  44.         read_info("config/config.info", doc);  
  45.   
  46.         print(cout, doc, -2);  
  47.     }  
  48.     catch (json_parser_error& e)  
  49.     {  
  50.         cout << e.what() << endl;  
  51.     }  
  52.     catch (std::exception& e)  
  53.     {  
  54.         cout << e.what() << endl;  
  55.     }  
  56. };  

如你所见,几乎是一个模子倒出来的,除了调用的读取方法略有区别。

这里统一给出以上代码所需要引用的头文件和命名空间:

[cpp]  view plain  copy
 
  1. #include <iostream>  
  2.   
  3. #include <boost/property_tree/ptree.hpp>  
  4. #include <boost/property_tree/xml_parser.hpp>  
  5. #include <boost/property_tree/json_parser.hpp>  
  6. #include <boost/property_tree/ini_parser.hpp>  
  7. #include <boost/property_tree/info_parser.hpp>  
  8.   
  9. using namespace boost;  
  10. using namespace std;  
  11.   
  12. using namespace boost::property_tree;  

为了节省点读者的时间,我就再费点事,把三个格式的示例文件都贴出来吧。

示例文件config.json如下:

[plain]  view plain  copy
 
  1. {  
  2.   "config" :   
  3.   {  
  4.     "main" :   
  5.     {  
  6.       "title" : "windows",  
  7.       "icon" : "main.ico",  
  8.       "comment" : "Main Fisrt Comment",  
  9.       "comment" : "Main Second Comment"  
  10.     },  
  11.       
  12.     "paths" :   
  13.     {  
  14.       "name" : "init",  
  15.       "comment" : "Paths Comment",  
  16.       "path" :   
  17.       {  
  18.         "level" : "1",  
  19.         "text" : "a.ini"  
  20.       },  
  21.       "path" :   
  22.       {  
  23.         "level" : "2",  
  24.         "text" : "b.ini"  
  25.       },  
  26.       "path" :   
  27.       {  
  28.         "level" : "3",  
  29.         "text" : "c.ini"  
  30.       }  
  31.     },  
  32.   
  33.     "links" :   
  34.     {  
  35.       "key" : "<>",  
  36.       "comment" : "Links Comment",  
  37.       "link" :   
  38.       {  
  39.         "level" : "1",  
  40.         "text" : "www.sina.com"  
  41.       },  
  42.       "link" :   
  43.       {  
  44.         "level" : "2",  
  45.         "text" : "www.sohu.com"  
  46.       },  
  47.       "link" :   
  48.       {  
  49.         "level" : "3",  
  50.         "text" : "www.163.com"  
  51.       }  
  52.     }  
  53.   }  
  54. }  
示例文件config.info如下:
[plain]  view plain  copy
 
  1. config   
  2. {  
  3.   main   
  4.   {  
  5.     title windows  
  6.     icon main.ico  
  7.     comment Main Fisrt Comment  
  8.     comment Main Second Comment  
  9.   }  
  10.     
  11.   paths   
  12.   {  
  13.     name init  
  14.     comment Paths Comment  
  15.     path   
  16.     {  
  17.       level 1  
  18.       text a.ini  
  19.     },  
  20.     path   
  21.     {  
  22.       level 2  
  23.       text b.ini  
  24.     },  
  25.     path   
  26.     {  
  27.       level 3  
  28.       text c.ini  
  29.     }  
  30.   }  
  31.   
  32.   links   
  33.   {  
  34.     key <>  
  35.     comment Links Comment  
  36.     link   
  37.     {  
  38.       level 1  
  39.       text www.sina.com  
  40.     }  
  41.     link   
  42.     {  
  43.       level 2  
  44.       text www.sohu.com  
  45.     }  
  46.     link   
  47.     {  
  48.       level 3  
  49.       text www.163.com  
  50.     }  
  51.   }  
  52. }  

示例文件config.ini如下:

[plain]  view plain  copy
 
  1. [config.main]  
  2. title="windows"  
  3. icon="main.ico"  
  4.   
  5. [config.paths]  
  6. name="init"  
  7.   
  8. [config.paths.path1]  
  9. level="1"  
  10. text=a.ini  
  11.   
  12. [config.paths.path2]  
  13. level="2"  
  14. text=b.ini  
  15.   
  16. [config.paths.path3]  
  17. level="3"  
  18. text=c.ini  
  19.   
  20. [config.links]  
  21. key="<>"  
  22.   
  23. [config.links.link1]  
  24. level="1"  
  25. text=www.sina.com  
  26.   
  27. [config.links.link2]  
  28. level="2"  
  29. text=www.sohu.com  
  30.   
  31. [config.links.link3]  
  32. level="3"  
  33. text=www.163.com  

1.5 路径和访问

了解了xml文件的读取,下面就要关心树形结构的访问了。在文章的开头我说过,property_tree支持类似于路径的快速访问机制,这是通过path_type实现的:

[cpp]  view plain  copy
 
  1. template <typename Key>  
  2. struct path_of;  
  3.   
  4. template <typename Ch, typename Traits, typename Alloc>  
  5. struct path_of< std::basic_string<Ch, Traits, Alloc> >  
  6. {  
  7.     typedef std::basic_string<Ch, Traits, Alloc> _string;  
  8.     typedef string_path< _string, id_translator<_string> > type;  
  9. };  
  10.   
  11. typedef typename path_of<Key>::type          path_type;  

我们看到,path_type特化后其实就是一个字符串,与我们熟知的目录路径是一致的。我们首先看一下如何根据path定位?这可以调试get_child函数的调用堆栈:

[cpp]  view plain  copy
 
  1.   template<class K, class D, class C>  
  2.   basic_ptree<K, D, C> &  
  3.       basic_ptree<K, D, C>::get_child(const path_type &path)  
  4.   {  
  5.       path_type p(path);  
  6.       self_type *n = walk_path(p);  
  7.       if (!n) {  
  8.           BOOST_PROPERTY_TREE_THROW(ptree_bad_path("No such node", path));  
  9.       }  
  10.       return *n;  
  11.   }  
  12.   
  13.   template<class K, class D, class C>  
  14.   basic_ptree<K, D, C> *  
  15.   basic_ptree<K, D, C>::walk_path(path_type &p) const  
  16.   {  
  17.       if(p.empty()) {  
  18.           // I'm the child we're looking for.  
  19.           return const_cast<basic_ptree*>(this);  
  20.       }  
  21.       // Recurse down the tree to find the path.  
  22.       key_type fragment = p.reduce();  
  23.       const_assoc_iterator el = find(fragment);  
  24.       if(el == not_found()) {  
  25.           // No such child.  
  26.           return 0;  
  27.       }  
  28.       // Not done yet, recurse.  
  29.       return el->second.walk_path(p);  
  30.   }  
  31.     
  32.   template<class K, class D, class C> inline  
  33.   typename basic_ptree<K, D, C>::const_assoc_iterator  
  34.       basic_ptree<K, D, C>::find(const key_type &key) const  
  35.   {  
  36.       return const_assoc_iterator(subs::assoc(this).find(key));  
  37.   }  
  38.   
  39.       static const by_name_index& assoc(const self_type *s) {  
  40.           return ch(s).BOOST_NESTED_TEMPLATE get<by_name>();  
  41.       }  
  42.         
  43.       static const base_container& ch(const self_type *s) {  
  44.           return *static_cast<const base_container*>(s->m_children);  
  45.       }  
  46.         
  47. template<typename Tag>  
  48. const typename index<Tag>::type& get()const BOOST_NOEXCEPT  
  49. {  
  50.   return *this;  
  51. }   

我们看到,第一个函数get_child会调用walk_path进行实际的检索,而第二个函数walk_path会将这个工作转给find,第三个函数find则直接找节点内部的那个子节点列表数据结构了。

了解了get_child函数,我们再看add函数:

[cpp]  view plain  copy
 
  1. template<class K, class D, class C>  
  2. template<class Type> inline  
  3. basic_ptree<K, D, C> & basic_ptree<K, D, C>::add(  
  4.     const path_type &path, const Type &value)  
  5. {  
  6.     return add(path, value,  
  7.                typename translator_between<data_type, Type>::type());  
  8. }  
  9.   
  10. template<class K, class D, class C>  
  11. template<class Type, typename Translator> inline  
  12. basic_ptree<K, D, C> & basic_ptree<K, D, C>::add(  
  13.     const path_type &path, const Type &value, Translator tr)  
  14. {  
  15.     self_type &child = add_child(path, self_type());  
  16.     child.put_value(value, tr);  
  17.     return child;  
  18. }  
  19.   
  20. template<class K, class D, class C>  
  21. basic_ptree<K, D, C> &  
  22.     basic_ptree<K, D, C>::add_child(const path_type &path,  
  23.                                     const self_type &value)  
  24. {  
  25.     path_type p(path);  
  26.     self_type &parent = force_path(p);  
  27.     // Got the parent.  
  28.     key_type fragment = p.reduce();  
  29.     return parent.push_back(value_type(fragment, value))->second;  
  30. }  

第一个add函数增加了translator参数,第二个add函数先用add_child增加子节点,再用put_value写属性值,第三个add_child函数,代码也比较简单,在路径定位后,在父节点的数据结构中增加value_type即可。

注意到上面写节点属性值用到了put_value方法,为什么不直接用data方法?我们知道,property_tree中节点上的属性数据可以用方法data直接访问,但我们读写的可不一定是一定是Data类型的数据,因此这里就需要put和get的泛型封装了。

首先看看get,我们根据get函数执行的调用堆栈,依此找到了以下函数:

[cpp]  view plain  copy
 
  1. template<class K, class D, class C>  
  2. template<class Type> inline  
  3. Type basic_ptree<K, D, C>::get_value() const  
  4. {  
  5.     return get_value<Type>(  
  6.         typename translator_between<data_type, Type>::type());  
  7. }  
  8.   
  9. template<class K, class D, class C>  
  10. template<class Type, class Translator>  
  11. typename boost::enable_if<detail::is_translator<Translator>, Type>::type  
  12. basic_ptree<K, D, C>::get_value(Translator tr) const  
  13. {  
  14.     if(boost::optional<Type> o = get_value_optional<Type>(tr)) {  
  15.         return *o;  
  16.     }  
  17.     BOOST_PROPERTY_TREE_THROW(ptree_bad_data(  
  18.         std::string("conversion of data to type \"") +  
  19.         typeid(Type).name() + "\" failed", data()));  
  20. }  
  21.   
  22. template<class K, class D, class C>  
  23. template<class Type, class Translator> inline  
  24. optional<Type> basic_ptree<K, D, C>::get_value_optional(  
  25.                                             Translator tr) const  
  26. {  
  27.     return tr.get_value(data());  
  28. }  
  29.   
  30.     boost::optional<E> get_value(const internal_type &v) {  
  31.         std::basic_istringstream<Ch, Traits, Alloc> iss(v);  
  32.         iss.imbue(m_loc);  
  33.         E e;  
  34.         customized::extract(iss, e);  
  35.         if(iss.fail() || iss.bad() || iss.get() != Traits::eof()) {  
  36.             return boost::optional<E>();  
  37.         }  
  38.         return e;  
  39.     }  

第一个函数get_value为函数调用增加了translator参数。第二个函数get_value通过boost::optional增加了节点是否存在的判断。第三个函数get_value_optional增加了data()参数,并让Translator去解决无问题,第四个函数get_value是在Translator内部对data()进行最后的转换。

再来看put函数:

[cpp]  view plain  copy
 
  1. template<class K, class D, class C>  
  2. template<class Type> inline  
  3. basic_ptree<K, D, C> & basic_ptree<K, D, C>::put(  
  4.     const path_type &path, const Type &value)  
  5. {  
  6.     return put(path, value,  
  7.                typename translator_between<data_type, Type>::type());  
  8. }  
  9.   
  10. template<class K, class D, class C>  
  11. template<class Type, typename Translator>  
  12. basic_ptree<K, D, C> & basic_ptree<K, D, C>::put(  
  13.     const path_type &path, const Type &value, Translator tr)  
  14. {  
  15.     if(optional<self_type &> child = get_child_optional(path)) {  
  16.         child.get().put_value(value, tr);  
  17.         return *child;  
  18.     } else {  
  19.         self_type &child2 = put_child(path, self_type());  
  20.         child2.put_value(value, tr);  
  21.         return child2;  
  22.     }  
  23. }  
  24.   
  25. template<class K, class D, class C>  
  26. template<class Type, class Translator>  
  27. void basic_ptree<K, D, C>::put_value(const Type &value, Translator tr)  
  28. {  
  29.     if(optional<data_type> o = tr.put_value(value)) {  
  30.         data() = *o;  
  31.     } else {  
  32.         BOOST_PROPERTY_TREE_THROW(ptree_bad_data(  
  33.             std::string("conversion of type \"") + typeid(Type).name() +  
  34.             "\" to data failed", boost::any()));  
  35.     }  
  36. }  
  37.   
  38.         boost::optional<internal_type> put_value(const E &v) {  
  39.         std::basic_ostringstream<Ch, Traits, Alloc> oss;  
  40.         oss.imbue(m_loc);  
  41.         customized::insert(oss, v);  
  42.         if(oss) {  
  43.             return oss.str();  
  44.         }  
  45.         return boost::optional<internal_type>();  
  46.     }  

第一个put函数增加了translator参数,第二个put函数通过get_child_optional增加了节点是否存在的判断,第三个put_value函数让Translator去解决问题,第四个put_value是在Translator内部对数据进行最后的转换。

本节的测试代码如下:

[cpp]  view plain  copy
 
  1. void visit_xml_demo(ptree& doc)  
  2. {  
  3.     ptree root = doc.get_child("config.main");  
  4.     root.add("<xmlattr>.ver""1");  
  5.   
  6.     string title = root.get<string>("<xmlattr>.title");  
  7.     assert(title == "windows");  
  8.     int ver = root.get<int>("<xmlattr>.ver");  
  9.     assert(ver == 1);  
  10.     root.put("<xmlattr>.ver", 2);  
  11. }  
代码比较简单,多跟踪几遍就一清二楚了。

1.6 xml文件的写入

了解了xml文件的读取,写入还很困难吗?确实,不过是read_xml和write_xml的区别而已:

[cpp]  view plain  copy
 
  1. template<class Ptree>  
  2. void write_xml(const std::string &filename,  
  3.                const Ptree &pt,  
  4.                const std::locale &loc = std::locale(),  
  5.                const xml_writer_settings<  
  6.                    typename Ptree::key_type  
  7.                > & settings = xml_writer_settings<typename Ptree::key_type>())  
  8. {  
  9.     std::basic_ofstream<typename Ptree::key_type::value_type>  
  10.         stream(filename.c_str());  
  11.     if (!stream)  
  12.         BOOST_PROPERTY_TREE_THROW(xml_parser_error(  
  13.             "cannot open file", filename, 0));  
  14.     stream.imbue(loc);  
  15.     write_xml_internal(stream, pt, filename, settings);  
  16. }  

如果仅仅是xml的read_xml然后write_xml确实没什么麻烦的,因为read_xml的时候其实已经建立的整个树形结构,然后再保存就可以了。这里真正需要注意的是如果没有xml文件呢?该如何凭空构造一个树形结构?通过对路径和访问一节的学习,这其实也不难,不过是反复调用add或add_child而已。这里还需要注意的是property_tree采用的依然是stl的值语义,因此只有在子节点都设置好了之后再加入父节点才能保证数据不丢失。

[cpp]  view plain  copy
 
  1. void write_xml_demo()  
  2. {  
  3.     ptree root;  
  4.   
  5.     ptree file_node;  
  6.     file_node.add("<xmlattr>.title""windows");    
  7.     file_node.add("<xmlattr>.size""10Mb");    
  8.     root.add_child("file", file_node);   
  9.   
  10.     root.add("<xmlcomment>""File Fisrt Comment");   
  11.     root.add("<xmlcomment>""File Second Comment");   
  12.   
  13.     {  
  14.         ptree paths_node;  
  15.         paths_node.add("<xmlattr>.attr""directory");    
  16.         paths_node.add("<xmlcomment>""Paths Comment");   
  17.   
  18.         ptree path_node;  
  19.         path_node.add("<xmlattr>.title""北京");  
  20.         path_node.put_value("abc");  
  21.         paths_node.add_child("path", path_node);    
  22.   
  23.         path_node = ptree();  
  24.         path_node.add("<xmlattr>.title""上海");  
  25.         path_node.put_value("efg");  
  26.         paths_node.add_child("path", path_node);    
  27.   
  28.         path_node = ptree();  
  29.         path_node.add("<xmlattr>.title""广州");  
  30.         path_node.put_value("hij");  
  31.         paths_node.add_child("path", path_node);    
  32.   
  33.         root.add_child("paths", paths_node);   
  34.     }  
  35.   
  36.     {  
  37.         ptree paths_node;  
  38.   
  39.         ptree path_node;  
  40.         path_node.add("<xmlattr>.title""111");  
  41.         path_node.put_value("klm");  
  42.         paths_node.add_child("path", path_node);    
  43.   
  44.         path_node = ptree();  
  45.         path_node.add("<xmlattr>.title""222");  
  46.         path_node.put_value("nop");  
  47.         paths_node.add_child("path", path_node);    
  48.   
  49.         path_node = ptree();  
  50.         path_node.add("<xmlattr>.title""333");  
  51.         path_node.put_value("qrs");  
  52.         paths_node.add_child("path", path_node);    
  53.   
  54.         root.add_child("paths", paths_node);   
  55.     }  
  56.   
  57.     ptree doc;  
  58.     doc.add_child("config", root);  
  59.   
  60.     try  
  61.     {  
  62.         xml_writer_settings<string> settings('\t', 1, "GB2312");    
  63.         write_xml("config/config.xml", doc, std::locale(), settings);   
  64.     }  
  65.     catch (std::exception& e)  
  66.     {  
  67.         cout << e.what() << endl;  
  68.     }  
  69. }  

代码比较简单,不解释了。其它几种格式的文件也类似。唯一需要注意的是因为ini文件无法支持超过2层的树形结构,注意一下树形结构的层数就是了。

1.7 UNICODE和UTF-8

以上的示例代码通通都是string和GB2312的,那么property_tree是否支持UNICODE和UTF-8呢?我第一次遇到这个问题是在解析SVG文件的时候,几乎收集上来的所有SVG文件都是UTF-8的,而且我们的开发环境又必须支持UNICODE。因为read_xml和write_xml两个方法中都有locale的参数,因此这个需求是很容易实现,唯一不爽的是boost的UTF-8转换需要引入utf8_codecvt_facet.hpp,而这又是必须编译成库才能使用组件。我知道这有些偏执了,尽管大多数boost组件不需要编译成库,但是我们永远也不能保证我们就一定不会用那些需要编译成库的组件。那么好吧,编译就编译吧。

[cpp]  view plain  copy
 
  1. #include <iostream>  
  2. #include <boost/lexical_cast.hpp>  
  3.   
  4. #include <boost/property_tree/ptree.hpp>  
  5. #include <boost/property_tree/xml_parser.hpp>  
  6.   
  7. #ifndef _UNICODE  
  8. #define tptree boost::property_tree::ptree  
  9. #else  
  10. #define tptree boost::property_tree::wptree  
  11. #endif   
  12.   
  13. #define BOOST_ALL_DYN_LINK  
  14. #include <boost/program_options/detail/convert.hpp>  
  15. #include <boost/program_options/detail/utf8_codecvt_facet.hpp>  
  16.   
  17. using namespace std;  
  18. using namespace boost;  
  19. using namespace ws;  
  20.   
  21. using namespace boost::property_tree;  
  22.   
  23. void load_svg(tptree& doc, const string& path)  
  24. {  
  25.     try  
  26.     {  
  27.         // 其中new的facet会被locale自动delete  
  28.         locale current_locale(locale(""), new program_options::detail::utf8_codecvt_facet());  
  29.         read_xml(path, doc, xml_parser::trim_whitespace, current_locale);  
  30.     }  
  31.     catch (std::exception& e)  
  32.     {  
  33.         cout << e.what() << endl;  
  34.     }  
  35. }  
  36.   
  37. void save_svg(tptree& doc, const string& path)  
  38. {  
  39.     try  
  40.     {  
  41.         // 其中new的facet会被locale自动delete  
  42.         locale current_locale(locale(""), new program_options::detail::utf8_codecvt_facet());  
  43.         xml_parser::xml_writer_settings<wstring> settings(_T('\t'), 1, _T("utf-8"));  
  44.         write_xml(path, doc, current_locale, settings);  
  45.     }  
  46.     catch (std::exception& e)  
  47.     {  
  48.         cout << e.what() << endl;  
  49.     }  
  50. }  

代码简单得几乎不需要解释,正好做一个轻松的结尾吧。如果以后再遇到property_tree中值得写成文字的内容,我会另开一篇文章。

参考:

boost xml keycompare 百度

你可能感兴趣的:(boost的property_tree组件)