添加子子以提升ptree

时间:2016-03-15 20:48:23

标签: c++ xml boost ptree

让我们说我的目标是以下列形式创建一个xml:

<main>
<elements>
    <element name="elem1"><temp/>
    </element>
    <element name="elem2"><temp/>
    </element>
</elements>
</main>

我有以下代码:

ptree pt;
pt.put("main","");

ptree temp1;
temp1.put("element","");
temp1.put("element.<xmlattr>.name","elem1");
temp1.put("element.temp");

ptree temp2;
temp2.put("element","");
temp2.put("element.<xmlattr>.name","elem2");
temp2.put("element.temp");

//temp1 represents the 1st <element>...</element>
//temp2 represents the 1st <element>...</element>

//Add temp1 and temp2 to <main> under <elements>

我认为以下方法可行:

pt.add_child("main.elements",temp1);
pt.add_child("main.elements",temp2);

然而,这会生成以下xml:

<main>
<elements>
    <element name="elem1"><temp/>
    </element>
</elements>
<elements>
    <element name="elem2"><temp/>
    </element>
<elements>
</main>

我能够通过以下形式制作我的temp1来获取所需的xml文件:

temp1.put("<xmlattr>.name","elem1");
temp1.put("temp","");
temp2.put("<xmlattr>.name","elem2");
temp2.put("temp","");
pt.add_child("main.elements.element",temp1);
pt.add_child("main.elements.element",temp2);

有没有办法可以使用我的初始temp1和temp2节点来获得所需的xml结构?

1 个答案:

答案 0 :(得分:4)

您的情况有点不理想(我非常支持您提供的工作片段。)

以下是可行的:

pt.add_child("main.elements.element", temp1.get_child("element"));
pt.add_child("main.elements.element", temp2.get_child("element"));

<强> Live On Coliru

#include <boost/property_tree/xml_parser.hpp>
#include <iostream>

using boost::property_tree::ptree;

int main() {
    ptree temp1;
    temp1.put("element.<xmlattr>.name","elem1");
    temp1.put_child("element.temp", {});

    ptree temp2;
    temp2.put("element.<xmlattr>.name","elem2");
    temp2.put("element.temp", "");

    //Add temp1 and temp2 to <main> under <elements>
    ptree pt;
    pt.add_child("main.elements.element", temp1.get_child("element"));
    pt.add_child("main.elements.element", temp2.get_child("element"));
    write_xml(std::cout, pt, boost::property_tree::xml_writer_make_settings<std::string>(' ', 4, "utf-8"));
}

打印

<?xml version="1.0" encoding="utf-8"?>
<main>
    <elements>
        <element name="elem1">
            <temp/>
        </element>
        <element name="elem2">
            <temp/>
        </element>
    </elements>
</main>