Monday, April 13, 2009

Qt4 Xml Object Mapper

I'm looking at Google App Engine, to realize my Web Services (Obviously with Python). Web Service Response are generally in XML, and in the 90% of the case you'll need to map Xml Response with your Objects.
I've written a simple class that allows you to handle this task in a easy way, and with a quite good flexibility.


class TestObject : public QObject {
Q_OBJECT

Q_PROPERTY(QString surname READ surname WRITE setSurname)
Q_PROPERTY(QUrl website READ website WRITE setWebSite)
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(int age READ age WRITE setAge)

...
};


The First step is writing Objects that inherit from QObject and adding your properties. The Mapper uses the introspection to assign the values.

Mapping and Introspection: Maybe you don't like the Xml Node Name as your property's name, in this case you can use the HashMap that allows you to say "Hei, the TagName 'A' is the property 'foo'!". There's also a protected virtual method called convertData that tries to covert Xml Node Text Value to your property's type, take a look at this example.


QString xml = "<personInfo>"
"<age>21</age>"
"<personName>Matteo</personName>"
"<surname>Bertozzi</surname>"
"<personWeb>http://th30z.netsons.org/</personWeb>"
"</personInfo>";

THXmlHashMap dataMapping;
dataMapping.insert("personName", "name");
dataMapping.insert("personWeb", "website");

TestObject obj;
THXmlMapper xmlMapper(&obj);
xmlMapper.setMapping(dataMapping);
xmlMapper.map(xml);
qDebug() << obj.name() << obj.surname() << obj.age() << obj.website();



Source Code is Available Here: Qt4 Xml Object Mapper.

1 comment:

  1. [...] to use the JSON Stream Reader. Maybe you can use it to create an automatic Object Mapper like the Xml Object Mapper that I’ve posted a couple of weeks [...]

    ReplyDelete