簡體   English   中英

添加子樹到boost :: property_tree元素

[英]Adding subtree to boost::property_tree element

我想要的是:

<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獲得所需的結果。 但沒有成功。 我必須使用哪些增強功能?

這行:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM