gpt4 book ai didi

c++ - 将子树添加到 boost::property_tree 元素

转载 作者:行者123 更新时间:2023-12-01 18:52:23 30 4
gpt4 key购买 nike

我想要的是这样的:

<tree>
<objects>
<object id="12345678">
<AdditionalInfo>
<Owner>Mr. Heik</Owner>
<Health>37/100</Health>
</AdditionalInfo>
</object>
</objects>
</tree>

我得到的是这样的:

<tree>
<objects>
<object id="12345678"/>
<AdditionalInfo>
<Owner>Mr. Heik</Owner>
<Health>37/100</Health>
</AdditionalInfo>
</objects>
</tree>

我尝试的是这样的:

using boost::property_tree::ptree;
ptree pt;
boost::property_tree::ptree nodeObject;
nodeObject.put("object.<xmlattr>.id", 12345678);

boost::property_tree::ptree nodeInfo;
nodeInfo.put("Owner", "Mr. Heik");
nodeInfo.put("Health", "37/100");

// Put everything together
nodeObject.put_child("AdditionalInfo", nodeInfo);
pt.add_child("tree.objects", nodeObject);
write_xml("output.xml", pt);

我尝试使用 put/add/add_child/etc 来获得所需的结果。但没有成功。我必须使用哪些 boost 功能?

最佳答案

这一行:

nodeObject.put("object.<xmlattr>.id", 12345678);

正在向具有给定属性的当前节点的子路径“对象”添加新的子节点。

只需在节点上设置属性即可:

nodeObject.put("<xmlattr>.id", 12345678);

并将节点直接添加到树中的正确路径:

pt.add_child("tree.objects.object", nodeObject);

最终代码:

ptree pt;
boost::property_tree::ptree nodeObject;
nodeObject.put("<xmlattr>.id", 12345678);

boost::property_tree::ptree nodeInfo;
nodeInfo.put("Owner", "Mr. Heik");
nodeInfo.put("Health", "37/100");

nodeObject.put_child("AdditionalInfo", nodeInfo);
pt.add_child("tree.objects.object", nodeObject);
write_xml("output.xml", pt);

输出:

<?xml version="1.0" encoding="utf-8"?>
<tree>
<objects>
<object id="12345678">
<AdditionalInfo>
<Owner>Mr. Heik</Owner>
<Health>37/100</Health>
</AdditionalInfo>
</object>
</objects>
</tree>

关于c++ - 将子树添加到 boost::property_tree 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24266703/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com