Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET XML Serialization and Null Collections

Tags:

I have a class with some collections in them, and I would like to serialize instances of this class to XML without having to initialize the collections to be empty, and without having to implement IXmlSerializable. I don't care if it creates empty elements, or doesn't create the elements at all. Just that it works without having to initialize a collection for each collection based property.

I have look at all the XML attributes I can decorate the properties with, and have not had any success with this. This seems like a simple thing to do that is can have an element or just none at all. Then when it is being deserialized it would just leave them null or ignore them period.

Here is a simple version of a class to use for working through this issue. Using this and the defaults you get an exception "Object reference not set to an instance of an object" due to the collections being null;

public class MyClass
{
    public string Name { get; set; }
    public bool IsAlive { get; set; }
    public List<Car> Cars { get; set; }
    public List<Home> Homes { get; set; }
    public List<Pet> Pets { get; set; }

    public void ToXmlFile(string fileName)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
        TextWriter writer = new StreamWriter(fileName);
        serializer.Serialize(writer, this);
        writer.Close();
    }
}

EDIT Thanks for the helps guys, it turns out the issue was in my GetHashCode method which didn't handle the null correctly. Once I fixed this all was good. I marked the first one to answer as being correct. Sorry for the Red Herring, but working through it with you guys did help.

like image 723
Rodney S. Foley Avatar asked Jan 26 '10 23:01

Rodney S. Foley


1 Answers

You do not need to initialize collections in order to serialize the class to XML. Here's a simple program to demonstrate:

class Program
{
    static void Main(string[] args)
    {
        MyClass c = new MyClass() { Name = "Test", IsAlive = true };
        XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
        using (MemoryStream ms = new MemoryStream())
        {
            serializer.Serialize(ms, c);
            Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
        }
        Console.ReadLine();
    }
}

This will print the following output:

<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Test</Name>
  <IsAlive>true</IsAlive>
</MyClass>

In other words, null collection properties behave the same way as any other null property - they don't get serialized at all (unless you change the default value, which I haven't).

like image 106
Aaronaught Avatar answered Oct 25 '22 00:10

Aaronaught