473,785 Members | 2,457 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Invalid OperationExcept ion" exception when
creating the serializer.

[XmlArrayItem (typeof(Interna lDataObject), ElementName="Te st"),
XmlArrayItem (typeof(Extende dDataObject), ElementName="Te st")]
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 5809
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.Collecti ons;
using System.Xml.Seri alization;

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(type of(DerivedClass )), XmlInclude(type of(BaseClass))]
public class Class1
{
static void Main(string[] args)
{
XmlTextWriter writer = null;
Class1 test = new Class1();
try
{
if (!File.Exists(" test.xml"))
{
File.Create("te st.xml");
}

writer = new XmlTextWriter(" test.xml", Encoding.Unicod e);
writer.Formatti ng = Formatting.Inde nted;
XmlSerializer serializer = new XmlSerializer(t ypeof(Class1));
serializer.Seri alize(writer, test);
}
catch(Exception caught)
{
Console.WriteLi ne(caught.ToStr ing());
}
finally
{
writer.Close();
}
}

public Class1()
{
myArray = new ArrayList();
myArray.Add(new BaseClass());
myArray.Add(new DerivedClass()) ;
}

[XmlArrayItem(ty peof(DerivedCla ss), ElementName="De rived")]
[XmlArrayItem(ty peof(BaseClass) , ElementName="Ba se")]
public ArrayList myArray;
}
}

"Hollywood" <ho************ @thzero.com> wrote in message
news:u1******** ******@tk2msftn gp13.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.Invalid OperationExcept ion" exception when
creating the serializer.

[XmlArrayItem (typeof(Interna lDataObject), ElementName="Te st"),
XmlArrayItem (typeof(Extende dDataObject), ElementName="Te st")]
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(type of(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 XmlAttributeOve rrides 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******** ******@tk2msftn gp13.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.Invalid OperationExcept ion" exception when
creating the serializer.

[XmlArrayItem (typeof(Interna lDataObject), ElementName="Te st"),
XmlArrayItem (typeof(Extende dDataObject), ElementName="Te st")]
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 XmlAttributeOve rrides 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
3076
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 I have to use an array PersonType in the AllPersonalData class. But if I have to implement the "Addition of PersonalType" (i.e. the step 2), I have to use ArrayList instead of a fixed length array. I know that I can use the ArrayList as an...
3
2230
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 string which contains a single xml node, I can serialize with this line of code: object = (object)serializer.Deserialize(new
4
8711
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 ds2 = (DataSet)formatter2.Deserialize(stream2); For the size of my DataSet, its taking 0.8 seconds to serialize and 2.3 seconds to deserialize.
0
7296
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 ago and it works fine. The question is if the ArrayList has a set of different objects of different type, every time different. We know what types should be involved, but we don't know what objects in what order and how many are used in the...
4
3319
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 it{him} and all objects in which it{he} is used, for example ArrayList Whether it is possible to bypass it somehow
3
2459
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 System.Collections.Comparer has 1 members, number of members deserialized is 0. at System.Runtime.Serialization.Formatters.Binary.ReadObjectInfo.GetMemberTypes(String
14
2429
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 StreamWriter.Flush() Dim writer As New IO.StreamWriter(System.Net.Sockets.TcpClient.GetStream) writer.Write(myArray)
1
4391
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 "System.InvalidCastException: Specified cast is not valid" in Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write5 _ArrayOfAnyType(Object o) of the temporary C# DLL that Web Service processing creates when serializing data.
0
9645
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.