3

QJson ( http://qjson.sourceforge.net ) 实现了一个非常方便的 API 用于序列化和反序列化 Q_OBJECTS - 通过将 Q_PROPERTIES 转换为 qVariant,它允许对任意模型实例进行方便的序列化和反序列化。

XML有类似的东西吗?QDom* 和 QXml* 系列都相当有限。

4

1 回答 1

2

据我所知,没有任何第三方库可以做到这一点。你有两个选择:

一个。手动编码每个对象的序列化/反序列化。这很容易。要序列化,请执行以下操作:

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;
}

反序列化:

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;
}

湾。克隆 QJSON 并重写发出 JSON 字符串的部分以发出 XML 字符串,反之亦然。应该是一天的工作时间。

于 2012-11-07T11:30:32.223 回答