我想将 XML 文件反序列化为 C# 对象。我的对象如下
[Serializable]
[XmlRoot(ElementName = "Collection")]
public class Collection
{
public Collection()
{
Artiesten = new List<Artiest>();
Albums = new List<Album>();
Nummers = new List<Nummer>();
}
[XmlElement("Artiesten")]
public List<Artiest> Artiesten { get; set; }
[XmlElement("Albums")]
public List<Album> Albums { get; set; }
[XmlElement("Nummers")]
public List<Nummer> Nummers { get; set; }
}
[Serializable]
public class Artiest
{
[XmlAttribute("artiestid")]
public int ArtiestId { get; set; }
[XmlElement(ElementName = "Naam")]
public String Naam { get; set; }
[XmlElement(ElementName = "Albums")]
public List<Album> Albums { get; set; }
}
[Serializable]
public class Nummer
{
[XmlAttribute("nummerid")]
public int NummerId { get; set; }
[XmlElement(ElementName = "titel")]
public String Titel { get; set; }
[XmlElement(ElementName = "duur")]
public String Duration { get; set; }
}
我的 XML 是这样的:
<Collection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Artiesten>
<Artiest artiestid="1">
<Naam>Harry</Naam>
<Albums>
<Album albumid="1">
<Titel>Album1</Titel>
<prijs valuta="Euro">19.99</prijs>
<uitgiftejaar>1999</uitgiftejaar>
<Nummers>
<Nummer nummerid="1">
<titel>happy Sundays</titel>
<duur>PT02M02S</duur>
</Nummer>
</Nummers>
</Album>
</Albums>
</Artiest>
</Artiesten>
<Albums>
<Album albumid="1">
<Titel>Album1</Titel>
<prijs valuta="Euro">19.99</prijs>
<uitgiftejaar>1999</uitgiftejaar>
<Nummers>
<Nummer nummerid="1">
<titel>Happy Sundays</titel>
<duur>PT02M02S</duur>
</Nummer>
</Nummers>
</Album>
</Albums>
<Nummers>
<Nummer nummerid="1">
<titel>Happy Sundays</titel>
<duur>PT02M02S</duur>
</Nummer>
</Nummers>
</Collection>
我试图像这样反序列化:
XDocument doc = XDocument.Load(file);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Collection));
using (var reader = doc.Root.CreateReader())
{
Collection collection = (Collection) xmlSerializer.Deserialize(reader);
}
由于某种原因,我找不到Collection
对象中的列表都是空的。调试显示加载的文件XDocument
是有效的。
编辑:我设法缩小了问题的范围。它确实正确反序列化列表,只有这些列表中对象的所有属性都是空的。