使用C ++ boost属性树在多个标签上使用相同属性的XML

时间:2017-05-30 20:12:02

标签: c++ xml boost

是否可以使用C ++ boost :: property_tree生成以下XML?

<tests>
    <test id="12" age="7">123</test>
    <test id="15" age="8">1rr</test>
    <test id="52" age="71">1qe3</test>
    <test id="72" age="5">1d5</test>
</tests>

我用过:

test.add("<xmlattr>.id", 12);
test.add("<xmlattr>.age", 8);
tests.add_child("test", test);
//Called multiple times

它产生了一个错误:

Attribute id Redefined

1 个答案:

答案 0 :(得分:2)

您需要创建单独的test元素:

<强> Live On Coliru

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

using boost::property_tree::ptree;

int main() {
    struct { int id, age; std::string value; } data[] = {
        { 12, 7, "123" },
        { 15, 8, "1rr" },
        { 52, 71, "1qe3" },
        { 72, 5, "1d5" },
    };

    ptree tests;

    for (auto& item : data) {
        ptree test;
        test.add("<xmlattr>.id", item.id);
        test.add("<xmlattr>.age", item.age);
        test.put_value(item.value);
        tests.add_child("test", test);
    };

    boost::property_tree::ptree pt;
    pt.add_child("tests", tests);
    write_xml(std::cout, pt, boost::property_tree::xml_writer_make_settings<std::string>(' ', 4));
}

打印:

<?xml version="1.0" encoding="utf-8"?>
<tests>
    <test id="12" age="7">123</test>
    <test id="15" age="8">1rr</test>
    <test id="52" age="71">1qe3</test>
    <test id="72" age="5">1d5</test>
</tests>