[英]boost property_tree adding nodes in a loop
How do you add nodes to a property tree while looping a array? 在循环数组时如何向属性树添加节点?
This is probably a simple thing but I just don't understand how to work with boost_property_tree. 这可能是一件简单的事情,但我只是不明白如何使用boost_property_tree。
I have an array of values that I want to add to a property tree and output it as xml. 我有一个值数组,我想添加到属性树并将其输出为xml。 If I hardcode the nodes and add them by hand to root node it works but if I try to do it from inside a loop the xml is invalid, contains only one node from the array and none of the xml nodes are terminate.
如果我硬编码节点并手动将它们添加到根节点,它可以工作,但如果我尝试从循环内部执行它,则xml无效,只包含数组中的一个节点,并且没有任何xml节点终止。
It's a variable length array of data so hardcoding the nodes are not possible. 它是一个可变长度的数据数组,因此无法对节点进行硬编码。 Doing something like this simply doesn't work.
做这样的事情根本行不通。 And I don't understand why?
我不明白为什么?
ptree listnode;
std::vector<data> dataarray= ...
for(auto data : dataarray)
{
ptree node;
...
listnode.add_child("value", node)
}
...
What I want is something like this: 我想要的是这样的:
<list>
<value active="true">12</value>
<value active="true">44</value>
<value active="true">23</value>
</list>
But the resulting xml looks like this: 但是生成的xml看起来像这样:
<list>
<value active="true">
It just stops after the first value node. 它只是在第一个值节点之后停止。 No exceptions or anything so I'm assuming that either my property_tree is invalid or its the xml_parser::write_xml that fails to create the xml.
没有例外或任何事情,所以我假设我的property_tree无效或xml_parser :: write_xml无法创建xml。
Most likely I have misunderstood how to use boost::property_tree. 我很可能误解了如何使用boost :: property_tree。 But really, outputting a list must be a pretty simple thing?
但实际上,输出列表必须是一件非常简单的事情吗?
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>
using namespace boost::property_tree;
int main() {
ptree pt;
auto& list = pt.add_child("list", ptree{});
for (auto data : { 12, 44, 23 })
list.add("value", data)
.add("<xmlattr>.active", true);
xml_parser::write_xml(std::cout, pt);
}
Resulting XML: 产生的XML:
<?xml version="1.0" encoding="utf-8"?>
<list>
<value active="true">12</value>
<value active="true">44</value>
<value active="true">23</value>
</list>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.