views:

30

answers:

2

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
            }
        }
    }
}
A: 

Using that exact code and XML, I get 1 item in _client.Reports (targeting 3.5 and 4.0 both). I'd make sure you're grabbing the right XML and using the right Report class. Maybe it's referring to one in a different namespace.

RandomEngy
Nope, it's a very small program with a custom namespace and there's only one Report class. Argh.
Nathan Loding
+2  A: 

Oh, I feel a little dumb now. My constructor for the Client class, when it initializes the List<Report> object, adds a default report to it. And then the XML adds the one it found. Thus doubling it. ::sigh::

Nathan Loding