Protocol Buffers are not always an option and you just have to serialize your data to XML. Then what? Luckily there is a serialization library available from Boost and it makes that pretty easy for us. You don’t even have to modify your existing data structures to write them out as XML: the library is non-invasive.

Let’s say I want to serialize a list of people to a file, and read it back later. My data structures would be defined like this:

And once a vector of person’s is serialized I want it to look something like this:

Easy! First you must define a generic serialize function for your data structure, then you instantiate an XML output archive with an ofstream object and pass it the data. Reading is done by instantiating an XML input archive with an ifstream object and loading the data into a variable. Like this:

Name  : Martin Vorbrodt
DOB   : 19800830
EMail : [email protected]

Name  : Dorota Vorbrodt
DOB   : 19810127
EMail : [email protected]

Program output.

The library has built in support for STL containers. It can also write the data in many output formats, not just XML. Luckily you only have to define one serialization function per data type and it will work with all input and output archives. Heck, you could even define a serialization function for your protocol buffers data types 😉

Leave a Reply