实际上我可以序列化,但我无法反序列化它。我需要有一个viewmodel的对象,所有的孩子都来自不稳定的输出,而且我也不确定我应该在哪里设置我的xml属性;模型或视图模型。
这是我的clss和viewmodel
public class Person
{
public string Name { get; set; }
readonly List<Person> children = new List<Person>();
public IList<Person> Children
{
get { return children; }
}
}
public class PersonViewModel : {
private ObservableCollection<PersonViewModel> children;
private Person person;
public PersonViewModel()
{
person = new Person();
}
public PersonViewModel(Person _person)
{
person = _person;
children = new ObservableCollection<PersonViewModel>(
(from child in _person.Children
select new PersonViewModel(child))
.ToList<PersonViewModel>());
}
[XmlElement("Name", typeof(string))]
public string Name
{
get
{
return person.Name;
}
set
{
person.Name = value;
this.RaisePropertyChanged("Name");
}
}
[XmlArray("Children", IsNullable = false), XmlArrayItem("Person"),]
public ObservableCollection<PersonViewModel> Children
{
get
{
return children;
}
}
}
这是我的代码已经生成的xml文件的内容。 但是当我想将它用于我的视图模型的对象类型时,子项将不会被现有数据初始化。
串行:
XmlSerializer xs = new XmlSerializer(typeof(PersonViewModel), new XmlRootAttribute { ElementName = "OrgChart" });
using (StreamWriter wr = new StreamWriter(System.AppDomain.CurrentDomain.BaseDirectory + "OrgChart.XML"))
{
xs.Serialize(wr, rootPerson);
}
解串器:
XmlSerializer xs = new XmlSerializer(typeof(PersonViewModel), new XmlRootAttribute { ElementName = "OrgChart" });
FileStream fs = new FileStream(filePath, FileMode.Open);
XmlReader reader = XmlReader.Create(fs);
rootPerson = SelectedItem = Profile = (PersonViewModel)xs.Deserialize(reader);
reader.Close();