Hi,
You need to use "XmlInclude" to include the types of your Internal- and
Extend Data Object.
Below is an example:
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Collections;
using System.Xml.Serialization;
namespace testserialize
{
[Serializable]
public class BaseClass
{
public BaseClass()
{
}
public int x = 5;
}
[Serializable]
public class DerivedClass : BaseClass
{
public DerivedClass()
{
}
public int y = 8;
}
public class Foo
{
public int Bar = 10;
}
/// <summary>
/// Summary description for Class1.
/// </summary>
[Serializable]
[XmlInclude(typeof(DerivedClass)), XmlInclude(typeof(BaseClass))]
public class Class1
{
static void Main(string[] args)
{
XmlTextWriter writer = null;
Class1 test = new Class1();
try
{
if (!File.Exists("test.xml"))
{
File.Create("test.xml");
}
writer = new XmlTextWriter("test.xml", Encoding.Unicode);
writer.Formatting = Formatting.Indented;
XmlSerializer serializer = new XmlSerializer(typeof(Class1));
serializer.Serialize(writer, test);
}
catch(Exception caught)
{
Console.WriteLine(caught.ToString());
}
finally
{
writer.Close();
}
}
public Class1()
{
myArray = new ArrayList();
myArray.Add(new BaseClass());
myArray.Add(new DerivedClass());
}
[XmlArrayItem(typeof(DerivedClass), ElementName="Derived")]
[XmlArrayItem(typeof(BaseClass), ElementName="Base")]
public ArrayList myArray;
}
}
"Hollywood" <ho************@thzero.com> wrote in message
news:u1**************@tk2msftngp13.phx.gbl...
First, is it possible to use XmlArrayItem to declare two data types, DT1
and DT2 where DT2 is a derived class, in an ArrayList as the same ElementName?
The following throws a "System.InvalidOperationException" exception when
creating the serializer.
[XmlArrayItem (typeof(InternalDataObject), ElementName="Test"),
XmlArrayItem (typeof(ExtendedDataObject), ElementName="Test")]
public virtual ArrayList Test
{
get { return m_alTest; }
set { m_alTest = value; }
}
Second, is it possible to dynamically add more XmlArrayItem, with typeof
metadata, attribute to a specific ArrayList during runtime to allow for
accounting of unknown, until run-time, derived types to be stored in the
ArrayList? It does not look like this is possible, but perhaps someone
has a sneaky trick or two.
Thanks!