Tôi cố gắng để làm một chút rất đơn giản của serialization với XmlSerializer:Setter không gọi khi deserializing bộ sưu tập
public struct XmlPerson
{
[XmlAttribute] public string Id { get; set; }
[XmlAttribute] public string Name { get; set; }
}
public class GroupOfPeople
{
private Dictionary<string, string> _namesById = new Dictionary<string, string>();
//pseudo property for serialising dictionary to/from XML
public List<XmlPerson> _XmlPeople
{
get
{
var people = new List<XmlPerson>();
foreach (KeyValuePair<string, string> pair in _namesById)
people.Add(new XmlPerson() { Id = pair.Key, Name = pair.Value });
return people;
}
set
{
_namesById.Clear();
foreach (var person in value)
_namesById.Add(person.Id, person.Name);
}
}
}
Saving lớp này hoạt động tốt, và tôi nhận được:
<?xml version="1.0" encoding="utf-8"?>
<GroupOfPeople xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<_XmlPeople>
<XmlPerson Id="person1" Name="Fred" />
<XmlPerson Id="person2" Name="Bill" />
<XmlPerson Id="person3" Name="Andy" />
<XmlPerson Id="person4" Name="Nagesh" />
</_XmlPeople>
</GroupOfPeople>
Tuy nhiên, khi Tôi đọc lại trong tập tin, thiết lập thuộc tính _XmlPeople của tôi không bao giờ được gọi, và do đó từ điển trống. Tất cả các thuộc tính khác trên đối tượng này nhận được tiền phạt deserialized.
Tôi có thiếu thứ gì đó hiển nhiên không? Tôi đã thử nhiều loại bộ sưu tập khác nhau nhưng không ai trong số họ deserialize.
EDIT: Đọc mã:
try
{
using (var stream = new StreamReader(itemPath))
{
var xml = new XmlSerializer(typeof(GroupOfPeople));
GroupOfPeople item = (GroupOfPeople)xml.Deserialize(stream);
}
}
//snip error stuff
làm cách nào để đọc? – Tigran
Đã chỉnh sửa bằng mã. – GazTheDestroyer
Thiết lập không bao giờ được gọi. Tôi có một breakpoint ngồi trên đó. – GazTheDestroyer