XML deserialization doubling up on entities

Posted by Nathan Loding on Stack Overflow See other posts from Stack Overflow or by Nathan Loding
Published on 2010-04-14T15:51:30Z Indexed on 2010/04/14 15:53 UTC
Read the original article Hit count: 591

Filed under:
|
|

I have an XML file that I am attempting to deserialize into it's respective objects. It works great on most of these objects, except for one item that is being doubled up on. Here's the relevant portion of the 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>

"Clients" is a List<Client> object. Each Client object has a List<Report> object within it. The issue is that when this XML is deserialized, the List<Report> object has a count of 2 -- the "First Report" Report object is in there twice. Why? Here's the 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
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml