【问题标题】:Qt XML serialization/deserialization to Q_PROPERTYQt XML 序列化/反序列化到 Q_PROPERTY
【发布时间】:2012-09-28 20:38:56
【问题描述】:

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

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

【问题讨论】:

    标签: xml qt serialization properties qtxml


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-09-25
      • 2011-05-12
      • 2011-05-03
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 2011-06-24
      相关资源
      最近更新 更多