Following code results in “unrecognized XML syntax” exception while writing to XML file.

However if I change xml_oarchive to text_oarchive or binary_oarchive, it works fine, so I assume it’s a bug in xml_oarchive ??? Does any one know how to fix this for xml_oarchive ???

 

 

#include <iostream>

#include <fstream>

#include <boost/archive/text_iarchive.hpp>

#include <boost/archive/text_oarchive.hpp>

#include <boost/archive/xml_iarchive.hpp>

#include <boost/archive/xml_oarchive.hpp>

#include <boost/archive/binary_iarchive.hpp>

#include <boost/archive/binary_oarchive.hpp>

#include <boost/serialization/vector.hpp>

#include <boost/serialization/map.hpp>

#include <vector>

#include <map>

#include <boost/archive/archive_exception.hpp>

#include <boost/archive/basic_xml_archive.hpp>

 

 

class base {

 

protected :

   std::vector<int> vec;

 

protected :

   friend class boost::serialization::access;

    template<class Archive>

    void serialize(Archive & ar, const unsigned int version)

    {

        ar & BOOST_SERIALIZATION_NVP(vec);

    }

public :

      void add(int i) { vec.push_back(i); }

      int get(int idx) { return vec[idx]; }

};

class derived : public base {

   friend class boost::serialization::access;

   std::map<std::string, int> hmap;

 

    template<class Archive>

    void serialize(Archive & ar, const unsigned int version)

    {

            ar & BOOST_SERIALIZATION_NVP(boost::serialization::base_object<base>(*this));

        ar & BOOST_SERIALIZATION_NVP(hmap);

    }

public :

      void add(std::string str, int i) { hmap[str] = i; base::add(i);   }

      int get(std::string str) { return hmap[str];    }

};

 

int main(int argc, char* argv[])

{

      try {

            derived A;

            A.add("First", 12);

            A.add("Second", 34);

const derived AA = A;

 

            std::ofstream ofs("Test.xml");

            assert(ofs.good());

            boost::archive::xml_oarchive oa(ofs);    

            oa << BOOST_SERIALIZATION_NVP(AA);

            ofs.close();

 

derived B;

            std::ifstream ifs("Test.xml");

            assert(ifs.good());

            boost::archive::xml_iarchive ia(ifs);

            ia >> BOOST_SERIALIZATION_NVP(B);

            ifs.close();

           

      }          

      catch (boost::archive::xml_archive_exception ex)

      {

            std::cerr << " X " << ex.what() << std::endl;

      }

      catch (boost::archive::archive_exception  ex)

      {

            std::cerr << " A " << ex.what() << std::endl;

      }

      catch (std::exception  ex)

      {

            std::cerr << " E " <<  ex.what() << std::endl;

      }

      catch (...)

      {

            std::cerr << "Unknown Exception " << std::endl;

      }

      return 0;

}