【问题标题】:Why can't XmlSerializer serialize this list object?为什么 XmlSerializer 不能序列化这个列表对象?
【发布时间】:2013-05-30 18:46:02
【问题描述】:

这是我的代码:

    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 和第二个字符串数组?

【问题讨论】:

    标签: c# wpf xml list serialization


    【解决方案1】:

    这是因为PaneData实现了IEnumerable&lt;string&gt;,序列化器不再关心任何其他属性,只使用枚举器。

    【讨论】:

    • 有什么办法可以解决这个问题还是我需要一个包装类?
    • 我会删除接口,实现IXmlSerializable 可能也可以,尽管这通常很痛苦。
    • 糟透了重新发明轮子。序列化太痛苦了。
    猜你喜欢
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多