473,503 Members | 2,105 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Serializing Classes

Hi

I wrote a class, Document, which has an Array of ITask objects. In order to
serialize the tasks contained within the tasks array, I marked each task
class with an attribute [Serializable], and added an entry to the task
collection property (of Document).

[
XmlElement("foo", typeof(FooTask)),
XmlElement("baa", typeof(BaaTask)),
XmlElement("taa", typeof(TaaTask)),
]
public TaskCollection Tasks
{
get { return m_tasks; }
}

The number of tasks has increased so I'm looking at possibilities to improve
maintenace. Is there a way I can dynamically create the mapping of element
name and its type for the array list? I would like to have a configuration
file with such information and load it at run time, rather than hardcoding
the element names.

Thanks
Werner
Nov 11 '05 #1
2 2123
Sure ... you can "attach" XmlElement attributes programmatically by
populating an XmlOverrides object and passing it to the constructor of the
XmlSerializer.

I pasted an old example that I had below. You can set up your XmlOverrides
object with settings you read from the app.config file with a custom section
handler for example or with the brand new configuration appliacation block.

--
HTH
Christoph Schittko [MVP]
Software Architect, .NET Mentor
"Werner B. Strydom" <bl*******@hotmail.com> wrote in message
news:uV**************@TK2MSFTNGP11.phx.gbl...
Hi

I wrote a class, Document, which has an Array of ITask objects. In order to serialize the tasks contained within the tasks array, I marked each task
class with an attribute [Serializable], and added an entry to the task
collection property (of Document).

[
XmlElement("foo", typeof(FooTask)),
XmlElement("baa", typeof(BaaTask)),
XmlElement("taa", typeof(TaaTask)),
]
public TaskCollection Tasks
{
get { return m_tasks; }
}

The number of tasks has increased so I'm looking at possibilities to improve maintenace. Is there a way I can dynamically create the mapping of element
name and its type for the array list? I would like to have a configuration
file with such information and load it at run time, rather than hardcoding
the element names.

Thanks
Werner

Nov 11 '05 #2
Here's the promissed example:

using System;
using System.Xml;
using System.Xml.Serialization;
using System.Collections;

// NO XmlInclude attributes
// to declare derived types
public class Vehicle
{
public Vehicle(){}
public string Make;
public string Model;
public int Year;
}
public class Car : Vehicle
{
public Car() {}
public string VIN;
}
public class Motorcycle : Vehicle
{
public Motorcycle() {}
public bool VeryLoud;
}

public class ParkingLot
{
public ArrayList Cars;
}

public class AttributeOverrides
{
public static void Main()
{
ParkingLot lot = SetupParkingLot();
XmlTextWriter writer = new XmlTextWriter( Console.Out );
writer.Formatting = Formatting.Indented;

Console.WriteLine( "Writing Parking Lot Without Runtime Attributes:" );
SerializeParkingLot( writer, lot );
Console.WriteLine( "" );
writer.Close();
// need another writer because
// we can't write two more than one root element with the
// same XmlTextWriter instance
XmlTextWriter anotherWriter = new XmlTextWriter( Console.Out );
anotherWriter.Formatting = Formatting.Indented;
Console.WriteLine( "\n\nWriting Parking Lot With Runtime Attributes:" );
SerializeCustomParkingLot( anotherWriter, lot );
anotherWriter.Close();
}

private static ParkingLot SetupParkingLot()
{
ParkingLot lot = new ParkingLot();
lot.Cars = new ArrayList();
Car wifesCar = new Car();
wifesCar.Make = "Ford";
wifesCar.Model = "Explorer";
wifesCar.Year = 1997;
wifesCar.VIN = "ABC123DEF";

lot.Cars.Add( wifesCar );

return lot;
}

private static void SerializeParkingLot(XmlWriter writer,
ParkingLot parkingLot)
{
XmlSerializer xs = new XmlSerializer( typeof(ParkingLot),
new Type[] { typeof(Car) } );

xs.Serialize( writer, parkingLot );
}

private static void SerializeCustomParkingLot(XmlWriter writer,
ParkingLot parkingLot)
{
XmlAttributes carsAttributes = new XmlAttributes();
XmlAttributes classAttributes =
new XmlAttributes();

classAttributes.XmlRoot =
new XmlRootAttribute("ParkingLotRoot");

carsAttributes.XmlArrayItems.Add( new
XmlArrayItemAttribute("ParkedCar", typeof(Car)));

XmlAttributeOverrides overrides =
new XmlAttributeOverrides();

overrides.Add(typeof(ParkingLot), classAttributes);
overrides.Add(typeof(ParkingLot), "Cars", carsAttributes);

try
{
XmlSerializer xs = new XmlSerializer(
typeof(ParkingLot), overrides );

xs.Serialize( writer, parkingLot );
}
catch( InvalidOperationException )
{
System.Console.WriteLine( "Bad override attributes" );
}
}

}

and here's a link to the configuration management application block:

http://www.gotdotnet.com/Community/W...e-fa4bf2e3080f
--
HTH
Christoph Schittko [MVP]
Software Architect, .NET Mentor
"Werner B. Strydom" <bl*******@hotmail.com> wrote in message
news:uV**************@TK2MSFTNGP11.phx.gbl...
Hi

I wrote a class, Document, which has an Array of ITask objects. In order to serialize the tasks contained within the tasks array, I marked each task
class with an attribute [Serializable], and added an entry to the task
collection property (of Document).

[
XmlElement("foo", typeof(FooTask)),
XmlElement("baa", typeof(BaaTask)),
XmlElement("taa", typeof(TaaTask)),
]
public TaskCollection Tasks
{
get { return m_tasks; }
}

The number of tasks has increased so I'm looking at possibilities to improve maintenace. Is there a way I can dynamically create the mapping of element
name and its type for the array list? I would like to have a configuration
file with such information and load it at run time, rather than hardcoding
the element names.

Thanks
Werner

Nov 11 '05 #3

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

Similar topics

4
353
by: Angelos Karantzalis | last post by:
Hi guys. I've come across a problem when I tried to serialize a class into xml, only to discover that the parent class's XML Serialization properties weren't included in the output xml. ...
2
3276
by: Aleksei Guzev | last post by:
Imagine one writing a class library CL1 for data storage. He defines classes ‘DataItem’ and ‘DataRecord’ so that the latter contains a collection of the former. And he derives class ‘IntItem’ from...
0
1313
by: Ante Smolcic | last post by:
Hi all, I have an ArrayList that contains items of type A. I declared the XmlArrayItem atribute for that type. Now I have an derived type B (from A) also contained in the ArrayList but I get...
4
2713
by: Wayne Wengert | last post by:
I am still stuck trying to create a Class to use for exporting and importing array data to/from XML. The format of the XML that I want to import/export is shown below as is the Class and the code I...
1
2067
by: Ivo Bronsveld | last post by:
All, I have quite a challenging task ahead of me. I need to write an object model (for code access) based on a schema, which cannot be made into a dataset because of it's complexity. So I...
10
8249
by: copx | last post by:
I want to save a struct to disk.... as plain text. At the moment I do it with a function that just writes the data using fprintf. I mean like this: fprintf(fp, "%d %d", my_struct.a, my_struct.b)...
2
3501
by: Tobias Zimmergren | last post by:
Hi, just wondering what serializing really is, and howto use it? Thanks. Tobias __________________________________________________________________ Tobias ICQ#: 55986339 Current ICQ status: +...
8
1388
by: Joe | last post by:
Hello All: Say I have a solution with two projects (Project1 and Project2) and each project contains a class (Project1 contains Class1 and Project2 contains Class2). The projects don't...
2
1331
by: Simon | last post by:
I'm developing a new application and want to use serialization as a way to save my data. But as I add new variables to my classes, how will serializing cope with that? For example, suppose I have...
2
697
by: she_prog | last post by:
I have a class derived from UserControl. I need to serialize an object of this class, but only some properties of it, as not all properties are serializable (some of the properties coming from...
0
7093
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...
0
7287
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
7348
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...
1
7006
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...
0
7467
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...
0
4685
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1519
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 ...
1
744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
397
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...

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.