Tôi có một lớp đơn giản kế thừa từ Bộ sưu tập và thêm một vài thuộc tính. Tôi cần phải tuần tự hóa lớp này thành XML, nhưng XMLSerializer bỏ qua các thuộc tính bổ sung của tôi.XmlSerialize bộ sưu tập tùy chỉnh với Thuộc tính
Tôi cho rằng điều này là do điều trị đặc biệt mà XMLSerializer cung cấp cho các đối tượng ICollection và IEnumerable. Cách tốt nhất xung quanh điều này là gì?
Dưới đây là một số mẫu mã:
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";
}
}
}
này kết quả đầu ra XML sau (lưu ý MyAttribute là mất tích trong các yếu tố 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>
Những gì tôi muốn là
<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>
Bất kỳ ý tưởng nào? Đơn giản càng tốt. Cảm ơn.
Xem giải pháp của tôi, bạn có thể thấy nó thú vị. – toddmo