我想要的是:
<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获得所需的结果。但没有成功。我必须使用哪些增强功能?
答案 0 :(得分:4)
这一行:
nodeObject.put("object.<xmlattr>.id", 12345678);
将新子项添加到子路径&#34; object&#34;具有给定属性的当前节点。
只需在节点上设置您的属性:
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>