libzeep

PrevUpHomeNext

Serialization

An alternative way to read/write XML files is using serialization. To do this, we first construct a structure called Person. We add a templated function to this struct just like in boost::serialize and then we can read the file.

#include <fstream>
#include <zeep/xml/document.hpp>

struct Person
{
    std::string firstname;
    std::string lastname;

    1template<class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        ar & zeep::make_nvp("firstname", firstname)
           & zeep::make_nvp("lastname", lastname);
    }
};

int main()
{
    2std::ifstream file("test.xml");
    zeep::xml::document doc(file);

    std::vector<Person> persons;
    3doc.deserialize("persons", persons);

    doc.clear();

    4doc.serialize("persons", persons);

    return 0;
}

1

A struct we want to serialize needs a serialize method

2

Read in a text document containing XML and parse it into a document object

3

Deserialize all persons into an array

4

Serialize all persons back into an XML document again

attributes

Suppose you want to serialize a value into a XML attribute, you would have to replace zeep::make_nvp with zeep::make_attribute_nvp.

custom types

What happens during serialization is deconstruction of structured data types into parts that can be converted into text strings. For this final conversion there are zeep::value_serializer helper classes. zeep::value_serializer is a template and specializations for the default types are given in <zeep/value_serializer.hpp>. You can create your own specializations for this class for custom data types, look at the one for boost::posix_time::ptime for inspiration.

enums

For conversion of enum's you can use the zeep::value_serializer specialization for enums:

enum class MyEnum { FOO, BAR };
zeep::value_serializer<MyEnum>::instance()
	("foo", MyEnum::FOO)
	("bar", MyEnum::BAR);

There's also a new interface, somewhat more intuitive from a modern C++ viewpoint:

enum class MyEnum { aap, noot, mies };
zeep::value_serializer<MyEnum>::init("MyEnum",
{
	{ MyEnum::aap, "aap" },
	{ MyEnum::noot, "noot" },
	{ MyEnum::mies, "mies" }
});

PrevUpHomeNext