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<string>
{
[XmlAttribute()]
public string MyAttribute { get; set; }
public MyCollection()
{
this.MyAttribute = "SerializeThis";
}
}
}
これにより、次の XML が出力されます (MyCollection 要素に MyAttribute がないことに注意してください)。
<?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>
何か案は?シンプルなほど良い。ありがとう。