我需要对XML文件进行简单的输入输出。我正在使用boost :: ptree。
struct structure
{
std::string str;
int ival;
std::list<bool> bval;
void save(const std::string& filename) {
ptree pt;
pt.put("main.str", str);
pt.put("main.ival", ival);
for (const auto& x : bval)
pt.put("main.bval.b", x);
write_xml(filename, pt);
}
void load(const std::string& filename) {
ptree pt;
read_xml(filename, pt);
str = pt.get("main.str", str);
ival = pt.get("main.ival", ival);
for(auto& v : pt.get_child("main.bval"))
bval.insert(v.second.data());
}
};
int main()
{
structure b, s;
s.str = "abc";
s.ival = 14;
s.bval = { 1, 0, 0, 1, 0, 1, 0, 0, 0, 1 };
try
{
s.save("zxx.xml");
b.load("zxx.xml");
}
catch (std::exception& exc)
{
std::cout << exc.what() << std::endl;
}
return 0;
}
输入无法正常工作,因为只有&#34; bval&#34;写在文件中。另外,我不知道如何输出这个容器(bval)。请帮忙!
答案 0 :(得分:1)
您只需将put
替换为add
即可。 “Put”假定不应重新创建密钥。
使用此修复程序,您可以进行往返:
s.save("zxx.xml");
b.load("zxx.xml");
b.save("zxx2.xml");
现在,您可以测试zxx.xml
是否等于zxx2.xml
。
查看 Live On Coliru 打印:
g++ -std=c++11 -Os -Wall -pedantic main.cpp && ./a.out && md5sum *.xml
8a91a9b67d3ac4518e59d23c90edabb0 zxx.xml
8a91a9b67d3ac4518e59d23c90edabb0 zxx2.xml
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <list>
#include <iostream>
using boost::property_tree::ptree;
struct structure
{
std::string str;
int ival;
std::list<bool> bval;
void save(const std::string& filename) {
ptree pt;
pt.put("main.str", str);
pt.put("main.ival", ival);
for (const auto& x : bval)
pt.add("main.bval.b", x);
write_xml(filename, pt);
}
void load(const std::string& filename) {
ptree pt;
read_xml(filename, pt);
str = pt.get("main.str", str);
ival = pt.get("main.ival", ival);
for(auto& v : pt.get_child("main.bval"))
{
bval.push_back(v.second.get<bool>(""));
}
}
};
int main()
{
structure b, s;
s.str = "abc";
s.ival = 14;
s.bval = { 1, 0, 0, 1, 0, 1, 0, 0, 0, 1 };
try
{
s.save("zxx.xml");
b.load("zxx.xml");
b.save("zxx2.xml");
}
catch (std::exception& exc)
{
std::cout << exc.what() << std::endl;
}
return 0;
}