XmlSerializer and types

2019-09-19 02:41发布

I have a class that handles XMLs serialization.

public class DB
{
    public List<Connection> lstConnections { get; set; }
    static string sRootAttribute = "Connections";

public static DB LoadFromFile(string path)
{
    FileStream fs = null;
    DB db = null;

    try
    {
        fs = File.Open(path, FileMode.Open);
        var serializer = new XmlSerializer(typeof(DB), new XmlRootAttribute(sRootAttribute));
        db = (DB)serializer.Deserialize(fs);
    }
    catch
    {

    }

    if (fs != null)
    {
        fs.Close();
    }

    return db;
}

public static void SaveToFile(string path, object objData)
{
    var fs = File.Open(path, FileMode.Create);
    var serializer = new XmlSerializer(objData.GetType(), new XmlRootAttribute(sRootAttribute));

    try
    {
        serializer.Serialize(fs, objData);
    }
    catch
    {

    }

    fs.Close();
}

}

The LoadFromFile method is somewhat generic, because it doesn't consider the serialized data type.
However, SaveToFile does GetType on the object that is being serialized.
Therefore, when I'm trying to deserialize the file with LoadFromFile I'm having problems. I'm not getting any exceptions, but the lstConnections is empty.

1条回答
唯我独甜
2楼-- · 2019-09-19 02:56

If you have ownership over the Connection class, then:

  1. Decorate the Connection class with [System.SerializableAttribute()] and [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)].
  2. Decorate the connections list property with [System.Xml.Serialization.XmlArrayItemAttribute("connection", IsNullable=false)]. Though I guess you will be safer with an array and a property that's not auto implemented.
  3. Decorate the DB class with: [System.SerializableAttribute()], [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] and [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
  4. All public properties of Connection that return primitive types will get automatically serialized. Unless you specifically decorate them with [System.Xml.Serialization.XmlAttributeAttribute()], then they'll be serialized as attributes.
  5. You must also handle serialization for non primitive return type properties of Connection similarly. Decorate properties that return collections with XmlArrayItemAttribute and mark each custom subtype as serializable.
查看更多
登录 后发表回答