【问题标题】:When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes当类从 List<> 继承时,XmlSerializer 不会序列化其他属性
【发布时间】:2011-07-01 10:40:13
【问题描述】:

我在这里遇到了一种情况,我需要从List&lt;ItemType&gt; 继承我的类,但是当我这样做时,XmlSerializer 不会序列化我的类中声明的任何属性或字段,以下示例演示:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        DoSerialize();
    }
    private void DoSerialize()
    {
        MyClass obj = new MyClass();
        obj.Add(1);
        obj.Add(2);
        obj.Add(3);
        XmlSerializer s = new XmlSerializer(typeof(MyClass));
        StringWriter sw = new StringWriter();
        s.Serialize(sw, obj);
    }
}
[Serializable]
[XmlRoot]
public class MyClass : List<int>
{
    public MyClass()
    {
    }
    int myAttribute = 2011;
    [XmlAttribute]
    public int MyAttribute
    {
        get
        {
            return myAttribute;
        }
        set
        {
            myAttribute = value;
        }
    }
}

生成的 XML:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <int>1</int>
  <int>2</int>
  <int>3</int>
</ArrayOfInt>

【问题讨论】:

  • 这是您通常不应继承 List 的众多原因之一。
  • @kirk:是的,我也是这么想的,但是这次我不得不,我没有开始项目,是这样的,我必须对其进行序列化
  • @Kirk 不同意该原则,但在这里(根据@driis 答案中的链接)问题实际上是实现IEnumerable 根本 意味着您自己的属性不不要被连载!这似乎很苛刻......
  • @AakashM 抱歉重复,我搜索但没有找到,可能是我使用了错误的关键字

标签: c# .net list xml-serialization ienumerable


【解决方案1】:

这里有一个你可以考虑的。

你可以有一个像这样的容器类:

class ContainerObject
{
     public int MyNewProperty { get; set; }

     [XmlElement("")]
     public List<int> MyList { get; set; }
}

诀窍是让 XmlElement name = "" 在 List 元素上方。

当它被序列化为 xml 时,你将拥有:

<ContainerObject>
   <MyNewProperty>...</MyNewProperty>

   <int>...</int>
   <int>...</int>

</ContainerObject>

如果您愿意,还可以为列表中的项目创建另一个类

 class MyItem
 {
     public int MyProperty {get;set;} 

 } 

然后有一个 MyItems 列表,而不是整数列表。

这是您控制列表中每个项目的 XmlElement 名称。

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    这是设计使然。我不知道为什么会做出这个决定,but it is stated in the documentation:

    • 实现 ICollection 或 IEnumerable 的类。只有集合是 序列化,而不是公共属性。

    (查看“可以序列化的项目”部分)。 Someone has filed a bug against this, but it won't be changed - 在这里,Microsoft 还确认不包括实现 ICollection 的类的属性实际上是 XmlSerializer 的行为。

    解决方法是:

    • 实现IXmlSerializable 并自行控制序列化。

    • 更改 MyClass 使其具有 List 类型的公共属性(并且不要对其进行子类化)。

    • 使用处理这种情况的 DataContractSerializer。

    【讨论】:

    • 我认为这就是答案,但我只是想确定一下,我问了因为我在文档中找不到它,谢谢
    • 嗨,5 年后在这里发现了这个问题。由于这仍然是一个问题 - 你将如何使用 DataContractSerializer 来做到这一点?
    • 你有没有试过用DataContractSerializer解决它。无法正常工作 (stackoverflow.com/questions/55301839/…)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多