问题描述
我想从我的app.config文件序列化存储/检索对象的集合。 (我使用的是code从杰夫·阿特伍德的博客文章最后的配置节处理..再访)。
I want to serialize a collection of objects for storage/retrieval from my app.config file. (I'm using the code from an example from Jeff Attwood's blog entry The Last Configuration Section Handler.. Revisited).
我想知道的,就是为什么类型的对象集合
What I want to know, is why collections of objects of type
public class MyClass
{
...
}
获得序列化到所谓的XML元素
get serialized to an xml element called
<ArrayOfMyClass>...</ArrayOfMyClass>
在这个例子中,我使用MyClass的对象的泛型列表。我也尝试创建一个新的类继承自列表和生成的XML是完全一样的。
In this example I'm using a generic list of MyClass objects. I've also tried creating a new class which inherits from List and the resultant xml is exactly the same.
有没有一种方法来覆盖使用的XML元素名称序列化/反序列化的时候?
Is there a way to override the xml element name used when serializing/deserializing?
推荐答案
当你从名单继承,你可以尝试沿着东西线
When you inherit from List you can try something along the lines of
[Serializable]
[System.Xml.Serialization.XmlRoot("SuperDuperCollection")]
public class SuperDuperCollection : List<MyClass> { ... }
来装饰你的类,使用不同的XMLATTRIBUTES应该让你有过的方式控制XML输出序列化时。
to decorate your class, using the different XmlAttributes should let you have control over the way the XML is output when serialized.
只是一个额外的编辑与一些测试code和输出:
Just an additional edit with some Test Code and output:
[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>
这篇关于如何序列化.NET集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!