【问题标题】:How to serialize collections in .net如何在.net中序列化集合
【发布时间】:2009-03-12 16:02:20
【问题描述】:

我想从我的 app.config 文件中序列化一组用于存储/检索的对象。 (我使用的代码来自 Jeff Attwood 的博客条目 The Last Configuration Section Handler.. Revisited 的示例)。

我想知道的是,为什么要收集类型的对象

public class MyClass
{
  ...
}

序列化为一个名为

的xml元素
<ArrayOfMyClass>...</ArrayOfMyClass> 

在本例中,我使用的是 MyClass 对象的通用列表。我还尝试创建一个继承自 List 的新类,生成的 xml 完全相同。

有没有办法覆盖序列化/反序列化时使用的 xml 元素名称?

【问题讨论】:

  • 用一个非常简单的解决方案更新了我的答案

标签: .net serialization


【解决方案1】:

当你从 List 继承时,你可以尝试一些类似的东西

[Serializable]
[System.Xml.Serialization.XmlRoot("SuperDuperCollection")]
public class SuperDuperCollection : List<MyClass> { ... }

为了装饰你的类,使用不同的 XmlAttributes 应该可以让你在序列化时控制 XML 的输出方式。

只是对一些测试代码和输出进行额外编辑:

[Serializable]
public class MyClass
{
public int SomeIdentifier { get; set; }
public string SomeData { get; set; }
}

....

SuperDuperCollection coll = new SuperDuperCollection
{
    new MyClass{ SomeData = "Hello", SomeIdentifier = 1},
    new MyClass{ SomeData = "World", SomeIdentifier = 2}
};

Console.WriteLine(XmlSerializeToString(coll));

输出:

<SuperDuperCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MyClass>
    <SomeIdentifier>1</SomeIdentifier>
    <SomeData>Hello</SomeData>
  </MyClass>
  <MyClass>
    <SomeIdentifier>2</SomeIdentifier>
    <SomeData>World</SomeData>
  </MyClass>
</SuperDuperCollection>

【讨论】:

  • 你可以不用额外的课程,检查我更新的答案
【解决方案2】:

如果它们是某个类型的子元素,则不会 - 您可以使用 [XmlRoot][XmlType][XmlElement][XmlArray][XmlArrayItem] 以各种组合来获得不同的结果 - 不幸的是,具体情况取决于确切的布局...

【讨论】:

    【解决方案3】:

    看看XmlArrayAttribute属性

    【讨论】:

      猜你喜欢
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多