将Qt XML序列化/反序列化为Q_PROPERTY

3

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

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

1个回答

2
据我所知,目前没有任何第三方库可以实现此功能。您有两个选项:
a. 为每个对象手动编写序列化/反序列化代码,这很容易实现。要进行序列化,请执行以下操作:
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 字符串,反之亦然。大约需要一天的工作时间。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接