为boost::property_tree元素添加子树

Adding subtree to boost::property_tree element

本文关键字:添加 元素 boost property tree      更新时间:2023-10-16

我想要的是:

<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/等来获得所需的结果。但是没有成功。我必须使用哪些增强功能?

这一行:

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

用给定的属性向当前节点的子路径"object"添加一个新的子路径。

在Node上设置你的属性:

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>