【问题标题】:Adding a sub child to boost ptree添加子子项以提升 ptree
【发布时间】:2016-07-01 12:20:18
【问题描述】:

假设我的目标是创建以下形式的 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 结构?

【问题讨论】:

    标签: c++ xml boost ptree


    【解决方案1】:

    您的情况有点欠佳(我非常赞成您提供的工作 sn-p)。

    以下是可行的:

    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>
    

    【讨论】:

    • 这只是一个例子。我可能会遇到从其他程序中获取元素的情况,我只需要将它添加到已经存在的树中。所以我把它放在这里,看看我是否遗漏了什么。我想您的解决方案适用于我的情况。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 2017-12-28
    • 2017-05-27
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多