【问题标题】:Adding subtree to boost::property_tree element将子树添加到 boost::property_tree 元素
【发布时间】:2014-06-17 14:41:12
【问题描述】:

我想要的是这个:

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

【问题讨论】:

    标签: c++ xml boost


    【解决方案1】:

    这一行:

    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>
    

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 2018-11-20
      相关资源
      最近更新 更多