将未命名的节点添加到boost :: property_tree :: ptree

sim*_*642 3 c++ boost boost-propertytree

我需要将未命名的节点添加到boost :: property_tree :: ptree,就像它的JSON解析器对数组一样.但是,当我想要这样做时,我在运行时得到这样的断言:

  Assertion failed: !p.empty() && "Empty path not allowed for put_child.", file C:\Program Files\Boost\boost\include/boost/property_tree/detail/ptree_implementation.hpp, line 877
Run Code Online (Sandbox Code Playgroud)

我这样做

tree.add_child(name, child);
Run Code Online (Sandbox Code Playgroud)

树和子都是ptree-s和名字char*.

我怎么能像ptree-s的JSON解析器那样做呢?

def*_*ode 12

我不认为Boost.Property_tree有一个很好的理由不允许空路径add_childput_child.在其内部路径实用程序中实现根检测的方式需要非空路径.

您可以通过在添加数组元素时不使用其路径实用程序来解决此问题.

using boost::property_tree::ptree;
ptree pt;
pt.put_child( "path.to.array", ptree() );
auto& array = pt.get_child( "path.to.array" );
array.push_back( std::make_pair( "", ptree("foo") ) );
array.push_back( std::make_pair( "", ptree("bar") ) );
boost::property_tree::json_parser::write_json( std::cout, pt, false );
// {"path":{"to":{"array":["foo","bar"]}}}
Run Code Online (Sandbox Code Playgroud)


tex*_*a83 6

我来到这里试图找出类似的问题.我花了一段时间来解决它,所以希望这篇文章可以帮助其他人.

对我来说,解决问题的关键是记住ptree是boost :: property_tree :: ptree :: value_type的集合.所以问题简化为"如何将value_types从一个ptree添加到另一个ptree".

Ptree为value_type插入提供了一些方法:

iterator push_front(const value_type &);
iterator push_back(const value_type &);
iterator insert(iterator, const value_type &);
Run Code Online (Sandbox Code Playgroud)

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));
Run Code Online (Sandbox Code Playgroud)

现在如果父输出为XML,它将包含:

<Value1>1</Value1>
<Value2>2</Value2>
Run Code Online (Sandbox Code Playgroud)