473,396 Members | 2,115 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Questions on Serialization and ArrayList

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!
Nov 12 '05 #1
5 5794
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!

Nov 12 '05 #2
Bennie,

Thanks, but that really doesn't answer the second portion of my query as it
assumes you know all the derived types that will be in a given list before
run-time begins. Thats a huge step backwards in terms of functionality for
arrays and collections.
You need to use "XmlInclude" to include the types of your Internal- and
Extend Data Object.

Nov 12 '05 #3
Even more frustrating is the following...

public class Test
{
....
public virtual ArrayList TestList
{
get { return m_alTest; }
set { m_alTest = value; }
}
....
}

[XmlInclude(typeof(B))]
public class A
{
....
}

public class B : A
{
....
public string MyValue2
{
get { return m_sMyValue; }
set { m_sMyValue = value;}
}
....
}

Serializing an instance of class Test that has one object, of type B, in
it's TestList gives you the following XML...

<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<TestList>
<anyType xsi:type="B">
<MyValue>1</MyValue>
</anyType>
</TestList>
</Test>

Of course, without the XmlInclude on class A it doesn't work. I should not
have to use the XmlInclude on class A to get the above XML, no excuses. The
serializer should assume since it has not been told of a class, that it
needs to write out the "xsi:type" attribute to define what class to
deserialize as.
Nov 12 '05 #4
1) No ... the XmlSerializer is pretty picky about only serializing XML that
it can deserialize as well. In your case the XmlSerializer cannot determine
which type it serialized, because you're assigning the same element name to
two different classes.

2) Yes, you can by passing an XmlAttributeOverrides object to the
XmlSerializer constructor. See [0] and [1] for more details.

--
HTH
Christoph Schittko [MVP, XmlInsider]
Software Architect, .NET Mentor

[0] http://www.topxml.com/xmlserializer/...tomization.asp
[1] http://www.topxml.com/xmlserializer/..._overrides.asp
"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!

Nov 12 '05 #5
> 1) No ... the XmlSerializer is pretty picky about only serializing XML
that
it can deserialize as well. In your case the XmlSerializer cannot determine which type it serialized, because you're assigning the same element name to two different classes.
Mms, can't it use the "xsi:type" attribute like it does in other
situations? It seems that its hit or miss on what it can and can't do
depending on situations.
2) Yes, you can by passing an XmlAttributeOverrides object to the
XmlSerializer constructor. See [0] and [1] for more details.


Thanks.. I'll take a look at those, probably missed those in my general
google search!
Nov 12 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Franz | last post by:
Let me describe the flow of my program first. 1. Deserialize data from xml file. 2. Addition of "PersonType" class to the AllPersonalData. 3. Serialize data back to the xml file. My question is...
3
by: Ice | last post by:
All - I'm pretty comfortable with simple XML serialization of objects. However I observed something the other day and I wanted to know if I solved it the right way. Basically if I have a...
4
by: hs | last post by:
Hi I am serializing a dataset using a binary formatter as follows: IFormatter formater = new BinaryFormatter(); formatter.Serialize(stream, ds); // ds=DataSet, stream=MemoryStream .... DataSet...
0
by: Just D. | last post by:
There is an interesting article - http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=542&printer=t It shows how to serialize the ArrayList of identical objects. I did it a year...
4
by: Alexander | last post by:
There was such problem, At compilation with SP1 (dotnetfx11SP1) On computers without him{it} недесериализуются some objects. For example (System. Collections. Comparer) and together with...
3
by: Alexander | last post by:
When i store rule on PC with .NET.SP1 i cant restore them from PC without SP1. An i get this Error: System.Runtime.Serialization.SerializationException: Possible Version mismatch. Type...
14
by: Tiraman :-\) | last post by:
Hi, i have a StreamWriter that hold a System.Net.Sockets.NetwrokStream and the StreamWriter Object Hold An ArrayList which i would like to Serialize And Send it back to the client via the...
1
by: Eric Porter | last post by:
Help! Below is some code for a Web Service which has two methods, First() and Second(). However, when the code is run, whichever of the two methods appears second in the source fails with...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.