Very simple C++ boost xml serialization example

#include <fstream>
#include <iostream>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>

using namespace std;

class Test {
private:    
    friend class boost::serialization::access;
    template<class Archive> void serialize(Archive & ar,
            const unsigned int version) {
        ar & BOOST_SERIALIZATION_NVP(a);
        ar & BOOST_SERIALIZATION_NVP(b);
        ar & BOOST_SERIALIZATION_NVP(c);
    }
    
    int a;
    int b;
    float c;
public:
    inline Test(int a, int b, float c) {
        this->a = a;
        this->b = b;
        this->c = c;
    }
};

int main() {
    std::ofstream ofs("filename.xml");

    Test* t = new Test(1, 2, 3.3);
    
    boost::archive::xml_oarchive oa(ofs);
    oa << BOOST_SERIALIZATION_NVP(t);
    
    return 0;
}

Posted by wojtek Sun, 22 Jun 2008 14:27:00 GMT




Comments

Leave a response

  1. amr over 1 year later:

    Nice example. How do you do the reverse method (xml -> instance object)?

    Thanks

  2. wojtek over 1 year later:

    http://www.boost.org/doc/libs/1_40_0/libs/serialization/doc/tutorial.html

    There you can find an example. I have not played with boost since I posted this stuff here.

Leave a comment