代码之家  ›  专栏  ›  技术社区  ›  Jerry

XmlSerializer不会序列化类中的所有内容

  •  1
  • Jerry  · 技术社区  · 16 年前

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

    [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<Product> . 但是我没有任何类属性:flag,A,B,C。

    我做错什么了吗?怎么了??

    谢谢你的回复。我不知道这是故意的。我已经转换成BinaryFormatter(用于二进制序列化),它工作得非常好。

    3 回复  |  直到 15 年前
        1
  •  7
  •   Jarek Kardas    16 年前

    下列的 msdn :

    问:为什么集合类的所有属性都没有序列化?

        2
  •  0
  •   SLaks    16 年前

    首先,在创建自己的集合类型时,应该继承 System.Collections.ObjectModel.Collection<T> ,这将允许您覆盖 InsertItem 和其他方法来获得对收集的完全控制。

    回答你的问题,, XmlSerializer 以不同方式处理集合类型以序列化集合中的项。它不会序列化任何属性(例如, List<T>.Capacity ).

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

        3
  •  -3
  •   Asaf    16 年前

    比如:

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