我想要的是:
<tree>
<objects>
<object id="12345678">
<AdditionalInfo>
<Owner>Mr. Heik</Owner>
<Health>37/100</Health>
</AdditionalInfo>
</object>
</objects>
</tree>
Run Code Online (Sandbox Code Playgroud)
我得到的是:
<tree>
<objects>
<object id="12345678"/>
<AdditionalInfo>
<Owner>Mr. Heik</Owner>
<Health>37/100</Health>
</AdditionalInfo>
</objects>
</tree>
Run Code Online (Sandbox Code Playgroud)
我试过的是:
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);
Run Code Online (Sandbox Code Playgroud)
我试图通过使用put / add / add_child / etc获得所需的结果。但没有成功。我必须使用哪些增强功能?
这行:
nodeObject.put("object.<xmlattr>.id", 12345678);
Run Code Online (Sandbox Code Playgroud)
正在使用给定属性将新的子项添加到当前节点的子路径“对象”中。
只需在节点上设置属性:
nodeObject.put("<xmlattr>.id", 12345678);
Run Code Online (Sandbox Code Playgroud)
并将节点直接添加到树中的正确路径:
pt.add_child("tree.objects.object", nodeObject);
Run Code Online (Sandbox Code Playgroud)
最终代码:
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);
Run Code Online (Sandbox Code Playgroud)
输出:
<?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>
Run Code Online (Sandbox Code Playgroud)