Introduction
This article provides simple classes and macros for simple C++ object initialization from an XML file. Here, the main goal is to achieve .INI files substitution, but it can be used for small data initialization needs as well.
Background
The XML data beeing processed is just a simple collection of XML elements containing (or not) attributes.
Using the code
Two classes are provided:
class CFromXMLObjectList : public CObList
{
public:
CFromXMLObjectList();
virtual ~CFromXMLObjectList();
BOOL FillFromXMLFile(CString xmlpath);
virtual BOOL FillFromXML(IXMLDOMNode* node)=0;
};
and:
class CFromXMLObject : public CObject
{
public:
CFromXMLObject();
virtual ~CFromXMLObject();
BOOL FillFromXMLFile(CString xmlpath,CString elementName);
virtual BOOL FillFromXML(IXMLDOMNode* node)=0;
};
The first one describes a list of objects to initialize from XML, and the second one is a simple object (without XML children).
In order to use these classes, you have to derive your objects from them, depending on the structure of your data.
For example:
class CCompany : public CFromXMLObjectList
{
public:
CCompany();
virtual ~CCompany();
DECLARE_XMLOBJ()
CString Dump();
private:
CString m_strName;
CString m_strAdress;
};
class CEmployee : public CFromXMLObject
{
public:
CEmployee();
virtual ~CEmployee();
DECLARE_XMLOBJ()
CString Dump();
private:
CString m_strName;
long m_lBirthYear;
long m_lBirthMonth;
long m_lBirthDay;
};
A few macros are provided (but you can easily add more if you need more features):
DECLARE_XMLOBJ()
=> in .h, every time an object is derived from CFromXMLObject
and has sub-objects and/or attributes.
DECLARE_XMLOBJLIST()
=> in .h, every time an object is derived from CFromXMLObjectList
and has only sub-objects and no attributes.
Macros for connecting member variables (can also be extended easily):
The easiest way to explain is by an example:
In Company.cpp:
BEGIN_XMLOBJ(CCompany)
XML_OBJ_MAP_STRING("Name",m_strName)
XML_OBJ_MAP_STRING("Adress",m_strAdress)
INNER_END_XMLOBJ()
BEGIN_INNER_OBJLIST()
XMLOBJLIST_MAP("EMPLOYEE",CEmployee)
END_XMLOBJLIST()
In Employee.cpp:
BEGIN_XMLOBJ(CEmployee)
XML_OBJ_MAP_STRING("Name",m_strName)
XML_OBJ_MAP_LONG("Year",m_lBirthYear)
XML_OBJ_MAP_LONG("Month",m_lBirthMonth)
XML_OBJ_MAP_LONG("Day",m_lBirthDay)
END_XMLOBJ()
You are being provided a few macros to connect an XML attribute to your member variable:
XML_OBJ_MAP_STRING
: simply stores the attribute in a member string variable.XML_OBJ_MAP_LONG
: converts the attribute to long
.XML_OBJ_MAP_DOUBLE
: converts to double
.XML_OBJ_MAP_BOOL
: converts to BOOL
.- I've not provided other data type connections, but it's very easy to expand those provided.
History
- 2008/04/14: first public version on CodeProject.