I have a Widget Class with a Parent and Child property of type Widget.
When you populate a set of Widgets, you set references to the Parent and Child.
I was using binary serialization, which works fine, but XML serialization does not. I believe this is a bug, as the .NET documentation states:
"When the class is serialized, the serialization engine keeps track of all referenced objects already serialized to ensure that the same object is not serialized more than once."
.....and...
"The serialization architecture provided with the .NET Framework correctly handles object graphs and circular references automatically. "
Code sample is below. To toggle the test cases, simply delete ONE of the / in the //*/ comment under "test one". If you remove the two lines that set up the parents (forming the parent references) the xml processing works fine. Otherwise the error returned is "There was an error generating the XML document.". Any ideas?
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
namespace SerializationBugTest
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Widget myWidget = new Widget();
myWidget.Name = "Top";
Widget myChildWidget = new Widget();
myChildWidget.Name = "Child";
Widget myGrandchild = new Widget();
myGrandchild.Name = "Grandchild";
myWidget.Child = myChildWidget;
myChildWidget.Child = myGrandchild;
// comment out these lines to make XML serialization work
myChildWidget.Parent = myWidget;
myGrandchild.Parent = myChildWidget;
Console.WriteLine(myWidget.Name);
Console.WriteLine(myGrandchild.Name);
Console.WriteLine(myGrandchild.Parent.Parent.Name) ;
Console.WriteLine(myWidget.Child.Parent.Child.Chil d.Name);
// test one
//*
Stream myStream ;
myStream = File.OpenWrite("Temp.bin");
if (myStream != null)
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(myStream, myWidget);
myStream.Close();
}
// test two
/*/
myWidget.Child = myChildWidget;
myChildWidget.Child = myGrandchild;
myChildWidget.Parent = myWidget;
myGrandchild.Parent = myChildWidget;
XmlSerializer x = new XmlSerializer(typeof(Widget));
TextWriter writer = new StreamWriter("Temp.xml");
x.Serialize(writer, myWidget);
writer.Close();
//*/
}
}
}