当前我试图序列化并反序列化一些我的类到XML。一种方式(列表 - > XML)完美工作(请参见下面的示例)。另一种方式将无法正常工作。 我想要反序列化的类包含另一个类的另一个列表。这在XML文件中也是正确的。但是当我反序列化这个类时,它将不起作用。XML(De)列表序列化
在下面的例子中,这意味着Foo类可以通过其List of Bars正确地序列化。但是,当我反序列化的XML文件只有FooString和其他属性被正确序列化。酒吧名单每次都是空的。调试器也不会随时进入。
有人能告诉我我做错了什么吗?
在此先感谢!
主被摄体看起来像这样:
[XmlInclude(typeof (Bar))]
[XmlRoot(ElementName = "Foo")]
public class Foo() : IFooInterface
{
[XmlElement("FooString")]
public string FooString
{
// For simplifaction auto proerty, normally with
// backing field
get;
set;
}
// Some other properties for the xml
// ...
// Dirty Hack to serialize the List, because an Interface could not be serialized
// I've already tried to remove this tag, to replace it with [XmlElement("BarList")], but nothing works
[XmlArray("BarList")]
[XmlArrayItem(ElementName = "Bar", Type = typeof(Bar))]
public List<Bar> XmlBarList
{
get
{
return this.BarList.Select(bar => bar as Bar).ToList();
}
set
{
this.BarList = new ObservableCollection<IBarInterface>(value);
}
}
private ObservableCollection<IBarInterface> barList;
[XmlIgnore]
public ObservableCollection<IBarInterface> BarList
{
get
{
return this.barList;
}
set
{
// For simplification removed Notification Proerties
this.barList = value;
}
}
}
嵌套类看起来像这样:
[XmlType("Bar")]
public class Bar : IBarInterface
{
[XmlElement("BarString")]
public string BarString
{
get;
set;
}
// Some other properties for the xml
// ...
}
该(解)序列化的类的类:
public class FooBarProvider()
{
// Won't work
// the BarList of any Foo item is everytime
// empty.
public List<Foo> Load()
{
var reader = new StreamReader("PathToTheXml.xml");
var serializer = new XmlSerializer(typeof(List<Foo>));
var list = (List<Foo>)serializer.Deserialize(reader);
}
// Works
public void Save(List<Foo> fooList)
{
var serializer = new XmlSerializer(typeof(List<Foo>));
var writer = new StreamWriter("PathToTheXml.xml");
serializer.Serialize(writer, fooList);
writer.Close();
}
}
这是生成的XML文件:
<ArrayOfFoo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Foo>
<BarList>
<Bar>
<BarString>Hello Bar!</BarString>
</Bar>
</BarList>
<FooString>Hello Foo!</FooString>
</Foo>
</ArrayOfFoo>
您好,感谢您的回复。但是这也没有奏效。我试过了。我也尝试删除标签,并让它自动决定。但是我所做的一切 - 它不会奏效:/你有另一种方法吗? – CodeRain
更新的代码。应该工作 – jdweng
谢谢你的工作:) – CodeRain