使用C++ boost属性树的多个标记具有相同属性的XML
问题描述:
可以使用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
答
您需要创建单独的test
元素:
#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>
谢谢,我加入'test.clear()'的问题解决了添加属性之前 –
@ Ja.L这正说明为什么你需要提供一个SSCCE/MVCE的例子。因为这样的事情不可能从你展示的代码中诊断出来;)可以节省每个人在那里的时间。更好的是,你可以经常在制作SSCCE时回答自己的问题(http://kera.name/articles/2013/10/nobody-writes-testcases-any-more/) – sehe