XmlSerialize具有Attribute的自定义集合

我有一个简单的类inheritance自Collection并添加了几个属性。 我需要将此类序列化为XML,但XMLSerializer忽略了我的其他属性。

我假设这是因为XMLSerializer提供ICollection和IEnumerable对象的特殊处理。 围绕这个最好的方法是什么?

这是一些示例代码:

using System.Collections.ObjectModel; using System.IO; using System.Xml.Serialization; namespace SerialiseCollection { class Program { static void Main(string[] args) { var c = new MyCollection(); c.Add("Hello"); c.Add("Goodbye"); var serializer = new XmlSerializer(typeof(MyCollection)); using (var writer = new StreamWriter("test.xml")) serializer.Serialize(writer, c); } } [XmlRoot("MyCollection")] public class MyCollection : Collection { [XmlAttribute()] public string MyAttribute { get; set; } public MyCollection() { this.MyAttribute = "SerializeThis"; } } } 

这将输出以下XML(注意MyCollection元素中缺少MyAttribute):

   Hello Goodbye  

想要的

  Hello Goodbye  

有任何想法吗? 越简越好。 谢谢。

collections品通常不会为额外的物业提供好地方。 在序列化和数据绑定期间,如果项看起来像集合( IListIEnumerable等 – 取决于场景),它们将被忽略。

如果是我,我会封装集合 – 即

 [Serializable] public class MyCollectionWrapper { [XmlAttribute] public string SomeProp {get;set;} // custom props etc [XmlAttribute] public int SomeOtherProp {get;set;} // custom props etc public Collection Items {get;set;} // the items } 

另一种选择是实现IXmlSerializable (相当多的工作),但这仍然不适用于数据绑定等。基本上,这不是预期的用法。

如果你进行封装,正如Marc Gravell建议的那样,本文的开头解释了如何让你的XML看起来与你描述的完全一样。

http://blogs.msdn.com/youssefm/archive/2009/06/12/customizing-the-xml-for-collections-with-xmlserializer-and-datacontractserializer.aspx

也就是说,而不是这个:

   Hello Goodbye   

你可以这样:

  Hello Goodbye  

正如尼尔·惠特克(Neil Whitaker)建议的那样,以防万一

创建内部集合以存储字符串并应用XmlElement属性来屏蔽集合名称。 生成相同的xml输出,就像MyCollectioninheritance自Collection一样,但也序列化父元素的属性。

 [XmlRoot("MyCollection")] public class MyCollection { [XmlAttribute()] public string MyAttribute { get; set; } [XmlElement("string")] public Collection unserializedCollectionName { get; set; } public MyCollection() { this.MyAttribute = "SerializeThis"; this.unserializedCollectionName = new Collection(); this.unserializedCollectionName.Add("Hello"); this.unserializedCollectionName.Add("Goodbye"); } } 

我一直在与Romaroo相同的问题进行斗争(想要在实现ICollection的类的xml序列化中添加属性)。 我没有找到任何方法来公开集合类中的属性。 我甚至尝试使用XmlAttribute标记并使我的属性显示为根节点的属性,但也没有运气。 然而,我能够在我的类上使用XmlRoot标签从“ArrayOf …”重命名它。 如果您有兴趣,可以参考以下内容:

  • MilkCarton.com
  • 微软论坛发帖
  • 迪拉尼耶 – 看上去一半

有时你只想做你想做的事; 框架被诅咒。

我在这里发布了一个答案列表的属性未反序列化

这就是OP想要做的事情。