【问题标题】:XmlSerializer doesn't serialize everything in my classXmlSerializer 不会序列化我课堂上的所有内容
【发布时间】:2009-11-25 16:02:14
【问题描述】:

我有一个非常基本的类,它是一个子类列表,以及一些摘要数据。

[Serializable]
public class ProductCollection : List<Product>
{
    public bool flag { get; set; }
    public double A { get; set; }
    public double B { get; set; }
    public double C { get; set; }
}


// method to save this class
private void SaveProductCollection()
{
    // Export case as XML...
    XmlSerializer xml = new XmlSerializer(typeof(ProductCollection));
    StreamWriter sw = new StreamWriter("output.xml");
    xml.Serialize(sw, theCollection);
    sw.Close();
}

当我致电SaveProductCollection() 时,我得到以下信息:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfProduct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Product>
    <InputType>1</InputType>
  </Product>
  <Product>
    <InputType>1</InputType>
  </Product>
</ArrayOfProduct>

请注意,我有基本类型:List&lt;Product&gt;。但我没有任何类属性:flag、A、B、C。

我做错了吗?怎么了??

更新感谢您的回复。我不知道这是设计使然。我已经转换为 BinaryFormatter(用于二进制序列化),效果很好。

【问题讨论】:

    标签: c# list xml-serialization ienumerable xmlserializer


    【解决方案1】:

    关注msdn

    问:为什么不是所有集合类的属性都被序列化了?

    答:XmlSerializer 仅在检测到 IEnumerable 或 ICollection 接口时序列化集合中的元素。此行为是设计使然。唯一的解决方法是将自定义集合重新分解为两个类,其中一个公开包含纯集合类型之一的属性。

    【讨论】:

      【解决方案2】:

      首先,在制作你自己的集合类型时,你应该继承System.Collections.ObjectModel.Collection&lt;T&gt;,这将允许你重写InsertItem和其他方法来获得对集合的完全控制。

      为了回答您的问题,XmlSerializer 以不同方式处理集合类型以序列化集合中的项目。它不会序列化任何属性(例如,List&lt;T&gt;.Capacity)。

      您可以将属性移动到包含属性或集合的不同类型。

      您也可以尝试使用attributes that control XML serialization,但我不确定他们是否会有所帮助。

      【讨论】:

        【解决方案3】:

        尝试将 XmlAttribute 添加到您的属性中,以便将它们序列化为属性。 比如:

         [XmlAttribute("flag")]
         public bool flag { get; set; }
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-24
        • 2013-04-30
        • 2021-09-03
        • 1970-01-01
        相关资源
        最近更新 更多