我有一个 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——“First Report”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
}
}
}
}