Xml序列化ICollection

时间:2015-03-12 17:08:48

标签: c# xml-serialization

我们正在开发一个具有适度复杂模型的项目,其核心类具有许多属性,这些属性是其他相关类的列表。我们在后端使用EF 6(代码优先),并且在遵循如何为该环境构建类的指导之后,我们大量使用了ICollection<T>

public class Product
{
    // a few normal properties
    public string Name { get; set; }
    public string Description { get; set; }
    public string Code { get; set; }
    // a large list of ICollection<T> properties
    public virtual ICollection<Rule> Rules { get; set; }
    public virtual ICollection<Update> Updates { get; set; }
    public virtual ICollection<Reference> References { get; set; }
    // more ICollections from here...
}

ICollection<T>引用的几个类本身都有集合(例如RuleICollection<Condition> Conditions),创建了一个相当深的复杂树。

现在我们的模型几乎已经完成,我们已经开始开发业务逻辑和UI(ASP.NET MVC)。系统所需的功能之一是将XML序列化/反序列化以与另一个系统进行交互。但是我们发现XmlSerialization.Serialize()不起作用,抱怨它不能序列化使用接口的东西。

当我们启动整个项目时,知道序列化将成为一个因素,我们构建了一组XSD并使用 xsd.exe 为我们生成类,我们已经修改了巨资。然而,该实用程序放入了一堆本应有助于序列化的标记,我们保留了所有这些:

[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute("product", Namespace = "", IsNullable = false)]
public class Product
{
    ....
}

不幸的是,我们遇到了无法序列化的问题,即使我们(理论上)告诉编译器,确实,这个类是可序列化的。每个子类都有一组类似的标签。所以,进行了更多的研究......

提供的解决方案here似乎带来了很多包袱。关于这个主题的其他SO答案似乎只是描述了ICollection<T>Collection<T>之间的区别,没有提供很多关于为什么你想要避免具体类的指导。我正在考虑将所有内容迁移到使用Collection<T>而不是ICollection<T>。如果我这样做,我会为自己带来未来的问题吗?

1 个答案:

答案 0 :(得分:0)

你试过IXmlSerializable吗?通过此界面,您可以控制写入和读取的内容。我不确定这是否可以帮助您解决问题。

    public CSortedList<string, CBasicStockData> Stocks { get; set; }
    public CSortedList<string, CIndustrySectorExchangeInfo> Exchanges { get; set; }
    public CSortedList<string, CIndustrySectorExchangeInfo> Industries { get; set; }
    public CSortedList<string, CIndustrySectorExchangeInfo> Sectors { get; set; }

    public void WriteXml(XmlWriter writer)
    {
        try
        {
            ///////////////////////////////////////////////////////////
            writer.WriteStartElement("Stocks");
            writer.WriteAttributeString("num", Stocks.Count.ToString());
            foreach (var kv in Stocks)
            {
                writer.WriteStartElement("item");
                foreach (var p in kv.Value.WritableProperties)
                {
                    var value = p.GetValue(kv.Value);
                    var str = (value == null ? string.Empty : value.ToString());
                    writer.WriteAttributeString(p.Name, str);
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            ///////////////////////////////////////////////////////////
            foreach (var propInfo in this.WritableProperties)
            {
                if (propInfo.Name == "Stocks") continue;
                dynamic prop = propInfo.GetValue(this);

                writer.WriteStartElement(propInfo.Name);
                writer.WriteAttributeString("num", prop.Count.ToString());
                foreach (var kv in prop)
                {
                    writer.WriteStartElement("item");
                    foreach (var p in kv.Value.WritableProperties)
                    {
                        var value = p.GetValue(kv.Value);
                        var str = (value == null ? string.Empty : value.ToString());
                        writer.WriteAttributeString(p.Name, str);
                    }
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            throw ex;
        }
    }

    public void ReadXml(XmlReader reader)
    {
        var propName = string.Empty;
        while (reader.Read() &&
            !(reader.NodeType == XmlNodeType.EndElement && reader.LocalName == this.GetType().Name))
        {
            if (reader.Name != "item")
            {
                propName = reader.Name;
                continue;
            }

            switch (propName)
            {
                case "Stocks":
                    {
                        var obj = new CBasicStockData();
                        foreach (var propInfo in obj.WritableProperties)
                        {
                            var value = reader.GetAttribute(propInfo.Name);
                            if (value == null)  //we may add new property to class after the file is created
                                continue;
                            propInfo.SetValue(obj, Convert.ChangeType(value, propInfo.PropertyType));
                        }
                        this.Stocks.Add(obj.Symbol, obj);
                        break;
                    }
                case "Exchanges":
                case "Industries":
                case "Sectors":
                    {
                        var obj = new CIndustrySectorExchangeInfo();
                        foreach (var p in obj.WritableProperties)
                        {
                            var value = reader.GetAttribute(p.Name);
                            if (value == null)
                                continue;
                            p.SetValue(obj, Convert.ChangeType(value, p.PropertyType));
                        }
                        var propInfo = this.WritableProperties.Find(x => x.Name == propName);
                        dynamic prop = propInfo.GetValue(this);
                        prop.Add(obj.Name, obj);
                        break;
                    }
                default:
                    break;
            }
        }
    }

    public static string XML_Serialize<T>(string filename, T myObject) where T : IXmlSerializable
    {
        XmlSerializer xmlSerializer = new XmlSerializer(myObject.GetType());
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;

        using (StringWriter stringWriter = new StringWriter())
        using (XmlWriter writer = XmlWriter.Create(stringWriter, settings)) {
            xmlSerializer.Serialize(writer, myObject);
            var xml = stringWriter.ToString(); // Your xml
            File.WriteAllText(filename, xml);
            return xml;
        }
    }
    public static void XML_DeSerialize<T>(string filename, out T myObject) where T : IXmlSerializable
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        using (StreamReader reader = new StreamReader(filename)) {
            myObject = (T)xmlSerializer.Deserialize(reader);
        }
    }
相关问题