all groups > dotnet xml > march 2006 >
You're in the

dotnet xml

group:

Serializing array of objects of different types


Serializing array of objects of different types geshas NO[at]SPAM gmail.com
3/28/2006 9:51:15 AM
dotnet xml:
Hello,

I need to serialize/deserialize array of non-typed objects to/from such
xml:

<contents>
<resource name="res1" />
<category name="cat1" />
<resource name="res2" />
<category name="cat2" />
</contents>

So that Contents object is array that consists of Resource or Category
objects. The problem is that while using XmlSerializer with
ICollection, the method item[] have to return object of some type (but
not just object). Otherwize it throws an error.
Before I'v been using 2 typed arrays (that consists of objects of type
Resource and Category correspondingly) inside Contents. But as
expected, it leads to that real order of items cannot be taken or set.
Now it's not acceptable..

How can I override or solve this problem? Need any advice.

BR, Evgeny
Re: Serializing array of objects of different types dickster
3/29/2006 3:50:30 AM
[quoted text, click to view]

Ok, this only answers part of your problem - but you did say "any
advice"

Obviously resource and category are still typed in this example but it
will mean you do not have to use 2 typed arrays & will allow you to
order your elements as they are added to the array..

Hopefully someone else will help further.

public class root
{
[XmlArrayItem("resource",typeof(resource))]
[XmlArrayItem("category",typeof(category))]
public Object[] contents;

}

public class resource
{
[XmlAttributeAttribute()]
public string name;
}

public class category
{
[XmlAttributeAttribute()]
public string name;
}

public class Run
{
public static void Main()
{
XmlSerializer s = new XmlSerializer(typeof(root));

root r = new root();

resource res1 = new resource();
res1.name ="res1";
resource res2 = new resource();
res2.name ="res2";
category cat1 = new category();
cat1.name ="cat1";
category cat2 = new category();
cat2.name ="cat2";

r.contents = new Object[4]{res1,cat1,res2,cat2};

s.Serialize(Console.Out, r);
Console.Read();

}
}
Re: Serializing array of objects of different types geshas NO[at]SPAM gmail.com
4/3/2006 9:03:29 AM
Hello,

Dickster, thank you very much for reply. Your advise put me the idea of
proper solution!
Best regards.
AddThis Social Bookmark Button