我有一個XML文件,我試圖反序列化到它的各個對象。它對大多數這些對象非常有用,除了一個項目被加倍。這裏是XML的相關部分:XML反序列化實體翻倍
<Clients>
<Client Name="My Company" SiteID="1"
GUID="xxx-xxx-xxx-xxx">
<Reports>
<Report Name="First Report" Path="/Custom/FirstReport">
<Generate>true</Generate>
</Report>
</Reports>
</Client>
</Clients>
「客戶端」是一個List<Client>
對象。每個Client
對象都有一個List<Report>
對象。問題是,當這個XML被反序列化時,List<Report>
對象的計數爲2--「第一個報告」Report
對象在那裏有兩次。爲什麼?這裏是C#:
public class Client {
[System.Xml.Serialization.XmlArray("Reports"), System.Xml.Serialization.XmlArrayItem(typeof(Report))]
public List<Report> Reports;
}
public class Report {
[System.Xml.Serialization.XmlAttribute("Name")]
public string Name;
public bool Generate;
[System.Xml.Serialization.XmlAttribute("Path")]
public string Path;
}
class Program
{
static void Main(string[] args)
{
List<Client> _clients = new List<Client>();
string xmlFile = "myxmlfile.xml";
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Client>), new System.Xml.Serialization.XmlRootAttribute("Clients"));
using (FileStream stream = new FileStream(xmlFile, FileMode.Open))
{
_clients = xmlSerializer.Deserialize(stream) as List<Client>;
}
foreach(Client _client in _clients)
{
Console.WriteLine("Count: " + _client.Reports.Count); // This write "2"
foreach(Report _report in _client.Reports)
{
Console.WriteLine("Name: " + _report.Name); // Writes "First Report" twice
}
}
}
}
不,它是一個非常小的程序,具有自定義命名空間,並且只有一個Report類。哎呀。 – 2010-04-14 18:48:57