我来到这里是为了解决类似的问题。花费了一些时间,最终解决了它,希望这篇文章对其他人有所帮助。
对于我来说,解决问题的关键在于记住ptree是boost :: property_tree :: ptree :: value_type的集合。因此,问题简化为“如何将一个ptree中的value_types添加到另一个ptree中”。
Ptree提供了一些value_type插入方法:
iterator push_front(const value_type &);
iterator push_back(const value_type &);
iterator insert(iterator, const value_type &);
Ptree没有const_reference typedef,因此我们无法使用back_inserter迭代器和std::copy。但是我们可以使用绑定函数和std::for_each。
#include <algorithm>
#include <functional>
#include <boost/property_tree/ptree.hpp>
using namespace std;
using namespace boost::property_tree;
...
ptree child;
child.put("Value1", 1);
child.put("Value2", 2);
ptree parent;
std::for_each(child.begin(),
child.end(),
std::bind(&ptree::push_back, &parent, placeholders::_1));
现在,如果将父级输出为XML,则会包含以下内容:
<Value1>1</Value1>
<Value2>2</Value2>