简体   繁体   中英

Why can't XmlSerializer serialize this list object?

Here is my code:

    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();
        }
    }

Here is what it gets serialized out to:

<?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>

Why do I not see S3 and the second array of strings in the serialization file?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM