我有一個簡單的類繼承自Collection並添加了一些屬性。我需要將此類序列化爲XML,但XMLSerializer忽略了我的其他屬性。XmlSerialize具有屬性的自定義集合
我認爲這是由於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<string>
{
[XmlAttribute()]
public string MyAttribute { get; set; }
public MyCollection()
{
this.MyAttribute = "SerializeThis";
}
}
}
此輸出下面的XML(注意MyAttribute缺少在MyCollection的元素):
<?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>
任何想法?越簡單越好。謝謝。
看到我的解決方案,您可能會覺得它很有趣。 – toddmo 2015-01-24 23:06:28