3

QJson (http://qjson.sourceforge.net) implements a very convenient API for serializing and deserializing Q_OBJECTS - by converting their Q_PROPERTIES to qVariant, it allows for a convenient serialization and deserialization of arbitrary model instances.

Is there anything similar for XML? Both QDom* and QXml* families are fairly limited.

reflog
  • 7,587
  • 1
  • 42
  • 47
qdot
  • 6,195
  • 5
  • 44
  • 95

1 Answers1

2

As far as I know, there aren't any 3rd party libraries that do that. You have two options:

a. Hand code the serialization/de-serialization for each object. It's pretty easy. To serialize, do something like:

QDomElement Asset::ToXMLNode(QDomDocument& doc)
{
    QDomElement elem = doc.createElement("Asset");
    elem.setAttribute("Image", ImageName);
    elem.setAttribute("Name", Description);
    elem.setAttribute("ID", ID);
    elem.setAttribute("TargetClass", ClassType);
    elem.setAttribute("Type", TypeToString());
    QDomElement physEl = doc.createElement("Physics");
    for(int i=0;i<BodyShapes.count();i++)
    {
        physEl.appendChild(BodyShapes[i]->ToXMLNode(doc));
    }
    elem.appendChild(physEl);
    return elem;
}

To deserialize:

void Asset::Load(const QDomElement& node)
{
    ImageName =  node.attribute("Image");
    Bitmap.load(GetResourceFolder() + QDir::separator() + ImageName);
    Description =  node.attribute("Name");
    ID =  node.attribute("ID");
    ClassType =  node.attribute("TargetClass");
    QDomNodeList shapes = node.firstChildElement("Physics").childNodes();
    for(int i=0;i<shapes.count();i++)
    {
        BodyShape* s = BodyShape::Load(shapes.item(i).toElement());
        BodyShapes << s;
    }
    IsLoaded = true;
}

b. Clone QJSON and just rewrite the parts that emit JSON strings to emit XML strings and vise-versa. Should be about a day of work.

reflog
  • 7,587
  • 1
  • 42
  • 47