2017-05-30 101 views
1

可以使用C++ boost :: property_tree生成以下XML嗎?使用C++ boost屬性樹的多個標記具有相同屬性的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

您需要創建單獨的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> 
+0

謝謝,我加入'test.clear()'的問題解決了添加屬性之前 –

+0

@ Ja.L這正說明爲什麼你需要提供一個SSCCE/MVCE的例子。因爲這樣的事情不可能從你展示的代碼中診斷出來;)可以節省每個人在那裏的時間。更好的是,你可以經常在製作SSCCE時回答自己的問題(http://kera.name/articles/2013/10/nobody-writes-testcases-any-more/) – sehe

相關問題