1

我需要对 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;
}

输入无法正常工作,因为文件中只有一个“bval”元素写入。另外,我不知道如何制作这个容器的输出(bval)。请帮忙!

4

1 回答 1

1

您应该简单地替换putadd. “Put”假定不应重新创建密钥。

通过此修复,您可以进行往返:

    s.save("zxx.xml");
    b.load("zxx.xml");
    b.save("zxx2.xml");

现在,您可以测试它zxx.xml是否等于zxx2.xml

看看它在 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;
}
于 2014-09-14T15:27:05.913 回答