De \ Serializing对象列表XML

时间:2015-01-11 19:39:07

标签: c# xml serialization xml-deserialization

我已经尝试过反序列化,但它不起作用。为什么会这样?当我序列化对象列表时,我要反序列化对象列表。可能吗 ?我尝试了一些东西,但它不是正确的方法。谢谢你的帮助。

我的代码:

主要:

Serialize(lstObservers);

 public void Serialize(List<Observer> list)
        {
           XmlSerializer serializer = new XmlSerializer(typeof(List<Observer>));
            using ( TextWriter writer = new StreamWriter( @"C:\Users\user\Desktop\MapSample\bin\Debug\ListObserver.xml"))
            {
                serializer.Serialize(writer, list);
            }  
        }

   private void DiserializeFunc()
        {
            var myDeserializer = new XmlSerializer(typeof(List<Observer>));
        using (var myFileStream = new FileStream(@"C:\Users\user\Desktop\MapSample\bin\Debug\ListObserver.xml", FileMode.Open))
        {
            listObservers = (List<Observer>)myDeserializer.Deserialize(myFileStream);
        }

        }

班级观察员:

    [Serializable()]
    public class Observer : MapObject
    {
        private int ID_Observer { get; set; }
        private double azimuth;
        private double Long;
        private double Lat;
        private double Lenght;
        private bool haveConnection;
        private bool DrawAzimuth;
        private XmlSerializer ser;

        /// <summary>
        /// C'tor
        /// </summary>
        public Observer(int ID_Observer = 0, double azimuth = 0, double Lat = 0, double Long = 0, double Lenght = 0, bool haveConnection = true, bool DrawAzimuth = true)
        {
            this.ID_Observer = ID_Observer;
            this.azimuth = azimuth;
            this.Long = Long;
            this.Lat = Lat;
            this.haveConnection = haveConnection;
            this.DrawAzimuth = DrawAzimuth;
            this.Lenght = Lenght;
        }

        public Observer()
        {
            ser = new XmlSerializer(this.GetType());
        }
}

编辑:我的建议是保存对象列表..如果有人有另一个想法,我将非常乐意学习。感谢

1 个答案:

答案 0 :(得分:1)

私有字段不会序列化。创建公共属性:

      [Serializable()]
  public class Observer : MapObject
  {

    private XmlSerializer ser;

    public int ID_Observer { get; set; }
    public double azimuth { get; set; }
    public double Long { get; set; }
    public double Lat { get; set; }
    public double Lenght { get; set; }
    public bool haveConnection { get; set; }
    public bool DrawAzimuth { get; set; }

    /// <summary>
    /// C'tor
    /// </summary>
    public Observer(int ID_Observer = 0, double azimuth = 0, double Lat = 0, double Long = 0, double Lenght = 0, bool haveConnection = true, bool DrawAzimuth = true)
    {
      this.ID_Observer = ID_Observer;
      this.azimuth = azimuth;
      this.Long = Long;
      this.Lat = Lat;
      this.haveConnection = haveConnection;
      this.DrawAzimuth = DrawAzimuth;
      this.Lenght = Lenght;
    }

    public Observer()
    {
      ser = new XmlSerializer(this.GetType());
    }
  }

enter image description here