Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing List<int> with XmlSerializer Causing Extra Items

Tags:

I'm noticing an odd behavior with the XmlSerializer and generic lists (specifically List<int>). I was wondering if anyone has seen this before or knows what's going on. It appears as though the serialization works fine but the deserialization wants to add extra items to the list. The code below demonstrates the problem.

Serializable class:

public class ListTest
{
    public int[] Array { get; set; }
    public List<int> List { get; set; }

    public ListTest()
    {
        Array = new[] {1, 2, 3, 4};
        List = new List<int>(Array);
    }
}

Test code:

ListTest listTest = new ListTest();
Debug.WriteLine("Initial Array: {0}", (object)String.Join(", ", listTest.Array));
Debug.WriteLine("Initial List: {0}", (object)String.Join(", ", listTest.List));

XmlSerializer serializer = new XmlSerializer(typeof(ListTest));
StringBuilder xml = new StringBuilder();
using(TextWriter writer = new StringWriter(xml))
{
    serializer.Serialize(writer, listTest);
}

Debug.WriteLine("XML: {0}", (object)xml.ToString());

using(TextReader reader = new StringReader(xml.ToString()))
{
    listTest = (ListTest) serializer.Deserialize(reader);
}

Debug.WriteLine("Deserialized Array: {0}", (object)String.Join(", ", listTest.Array));
Debug.WriteLine("Deserialized List: {0}", (object)String.Join(", ", listTest.List));

Debug output:

Initial Array: 1, 2, 3, 4
Initial List: 1, 2, 3, 4

XML:

<?xml version="1.0" encoding="utf-16"?>
<ListTest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Array>
    <int>1</int>
    <int>2</int>
    <int>3</int>
    <int>4</int>
  </Array>
  <List>
    <int>1</int>
    <int>2</int>
    <int>3</int>
    <int>4</int>
  </List>
</ListTest>
Deserialized Array: 1, 2, 3, 4
Deserialized List: 1, 2, 3, 4, 1, 2, 3, 4

Notice that both the array and list appear to have serialized to XML correctly but on deserialization the array comes out correct but the list comes back with a duplicate set of items. Any ideas?