XMLSERIALIZE自定义集合与属性
我有一个简单的类继承自Collection,并增加了一些特性。我需要序列化这个类XML,但是XmlSerializer的会忽略我的附加属性。
I've got a simple class that inherits from Collection and adds a couple of properties. I need to serialize this class to XML, but the XMLSerializer ignores my additional properties.
我想这是因为特殊的治疗,XMLSerializer的给人的ICollection和IEnumerable对象。什么是最好的方式解决此问题?
I assume this is because of the special treatment that XMLSerializer gives ICollection and IEnumerable objects. What's the best way around this?
下面是一些示例code:
Here's some sample code:
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<string>
{
[XmlAttribute()]
public string MyAttribute { get; set; }
public MyCollection()
{
this.MyAttribute = "SerializeThis";
}
}
}
该输出下面的XML(注意MyAttribute是在MyCollection的元素缺失):
This outputs the following XML (note MyAttribute is missing in the MyCollection element):
<?xml version="1.0" encoding="utf-8"?>
<MyCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Hello</string>
<string>Goodbye</string>
</MyCollection>
我的需要的是
<MyCollection MyAttribute="SerializeThis"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Hello</string>
<string>Goodbye</string>
</MyCollection>
任何想法?越简单越好。谢谢你。
Any ideas? The simpler the better. Thanks.
类别一般不作额外性能好地方。无论是在序列化和数据绑定,如果该项目看起来像一个集合,他们将被忽略(的IList
,的IEnumerable
,等等 - 具体取决于该方案)
Collections generally don't make good places for extra properties. Both during serialization and in data-binding, they will be ignored if the item looks like a collection (IList
, IEnumerable
, etc - depending on the scenario).
如果是我,我会封装集合 - 即
If it was me, I would encapsulate the collection - i.e.
[Serializable]
public class MyCollectionWrapper {
[XmlAttribute]
public string SomeProp {get;set;} // custom props etc
[XmlAttribute]
public int SomeOtherProp {get;set;} // custom props etc
public Collection<string> Items {get;set;} // the items
}
另一种选择是要落实的IXmlSerializable
(相当多的工作),但仍然不能用于数据绑定等,基本上,这是不是预期使用。
The other option is to implement IXmlSerializable
(quite a lot of work), but that still won't work for data-binding etc. Basically, this isn't the expected usage.