2013-05-30 90 views
0

这里是我的代码:为什么XmlSerializer无法序列化这个列表对象?

private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     PaneData data = new PaneData(); 
     data.Add("S1"); 
     data.Add("S2"); 
     data.SerializableLogFilters.Add("S3"); 
     XmlSerializer serializer = new XmlSerializer(typeof(PaneData)); 
     FileStream stream = new FileStream("Test.xml", FileMode.Create); 
     StreamWriter streamWriter = new StreamWriter(stream); 
     serializer.Serialize(streamWriter, data); 
     streamWriter.WriteLine(String.Empty); 
     streamWriter.Flush(); 
     stream.Close(); 
    } 

    public class PaneData : IEnumerable<string>, INotifyCollectionChanged 
    { 

     public List<string> RowList { get; set; } 

     public List<string> SerializableLogFilters { get; set; } 

     public event NotifyCollectionChangedEventHandler CollectionChanged; 

     public PaneData() 
     { 
      RowList = new List<string>(); 
      SerializableLogFilters = new List<string>(); 
     } 

     protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) 
     { 
      if (CollectionChanged != null) 
      { 
       CollectionChanged(this, e); 
      } 
     } 

     public void Add(string item) 
     { 
      RowList.Add(item); 
      OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item)); 
     } 

     public IEnumerator<string> GetEnumerator() 
     { 
      return RowList.GetEnumerator(); 
     } 

     System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 
     { 
      return GetEnumerator(); 
     } 
    } 

下面是它被序列化出来:

<?xml version="1.0" encoding="utf-8"?> 
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <string>S1</string> 
    <string>S2</string> 
</ArrayOfString> 

为什么我没有看到S3和序列化文件中的字符串的第二阵列?

回答

1

这是因为PaneData implements IEnumerable<string>,序列化程序不再关心任何其他属性,只是使用枚举器。

+0

有没有办法解决这个问题,还是我需要一个包装类? – Alexandru

+1

我会删除接口,实现'IXmlSerializable'可能也适用,尽管这通常很痛苦。 –

+0

吮吸重新发明轮子。序列化是如此的痛苦。 – Alexandru

相关问题