Search code examples
c++xmltinyxml

Is it possible to use TinyXML2 (or any other library) to convert structure or class directly to XML file and viceversa?


I have number of structures that look like this:

struct A
{
    long lValueA;
    BOOL bValueA;
    CString strValueA;
}; 
struct B
{
    long lValueB;
    BOOL bValueB;
    CString strValueB;
}; 
struct C
{
    A a;
    vector<B> vecB;
}; 

Is it possible to use TinyXML2 (or any other library) to convert it into XML file without manually pass each member variable from struct C? what I want will look like this:

main()
{
  C c;
  // Some code to initialise member variable of struct C

  // pass object/structure to XML parser to get XML file.
  Some_XML_Library_Object.parse( c ); 
  Some_XML_Library_Object.SaveFile("FilePath/Name.xml");

  // Also it would be nice if we can update values in structure or class directly like this
  const char* XML_File_Path = "FilePath/Name.xml";
  Some_XML_Library_Object.updateValueOfStructureFromXML(&c,XML_File_Path)
}

The XML File produce look similar to this:

<?xml version="1.0" encoding="UTF-8"?>
<A>
    <lValueA>
        value
    </lValueA>

    <bValueA>
        value
    </bValueA>

    <strValueA>
        value
    </strValueA>
</A>

<B>
    <lValueB>
        value
    </lValueB>
      ...
      ...
</B>

Thanks in advance.


Solution

  • You could use boost::serialisation to do something like what you asked...

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

    it has extensive capabilities for handling XML (and other formats) from the above page:

    In this tutorial, we have used a particular archive class - text_oarchive for saving and text_iarchive for loading. text archives render data as text and are portable across platforms. In addition to text archives, the library includes archive class for native binary data and xml formatted data. Interfaces to all archive classes are all identical. Once serialization has been defined for a class, that class can be serialized to any type of archive.

    Edit: you'd handle objects and serialize them rather than manipulate the XML directly to change values.