-
August 26th, 2003, 08:40 AM
#1
Convert C/C++ objects to XML strings
I’m looking for a way to serialize data that is represented as C/C++ struct/classes.
The final goal is to develop a mechanism that will convert my objects to a binary format so I could send them via network and then recreate… Something like MFC's Serialization support, but less complecated...
I’m thinking about using XML to convert the objects to strings. I hope there is a code somewhere that already does something like that…
Please Help!!!
-
August 26th, 2003, 08:55 AM
#2
Well, you could use .net as it has this functionality built in already. Otherwise converting a specific object to XML is fairly straight forward, however converting any generic object is rather complex. The difference is that with one of your objects, you know what's important to pass, what the structures are, and can dereference the pointers, etc. for any object you'd have to be able to extract that information and then convert to XML.
bytz
--This signature left intentionally blank--
-
August 26th, 2003, 09:47 AM
#3
Thanks!
Thanks for your attention to my question!
Honestly, this was my feeling too – there is no way to create a generic logic that will convert any object to a byte scream because objects can be very different, especially in the way they manage the recourses.
So basically the conclusion is that you have to provide each object with a procedure that explains how to serialize/deserialize its members, right? Do you know about any standard approaches? What do you think about using MFC Serialization w/CArchive ?
Thanks a lot for your help!
-
August 26th, 2003, 10:20 AM
#4
You could do this pretty quickly with templates:
Code:
CXMLSerializer
{
public:
CXMLSerializer()
{
m_xml << "<?xml version="1.0">" << std::endl;
}
template<typename T>
void Write( const std::string& name, const T& t )
{
m_xml << "<" << name << ">" << t << "</" << name << ">" << std::endl;
}
void Write( const std::string& name, const T* t )
{
Write( *t );
}
void Write( const std::string& name, const char* s )
{
m_xml << "<" << name << ">" << s << "</" << name << ">" << std::endl;
}
std::string Xml()
{
return m_xml.str();
}
public:
std::stringstream m_xml;
};
usage:
Code:
struct s
{
int x;
char* r;
std::string s;
float f;
std::string ToXml()
{
CXMLSerializer xml;
xml.Write( "x", x );
xml.Write( "r", r );
xml.Write( "s", s );
xml.Write( "f", f );
return xml.Xml();
}
};
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|