473,763 Members | 8,483 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 2133
Sure ... you can "attach" XmlElement attributes programmaticall y 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*******@hotm ail.com> wrote in message
news:uV******** ******@TK2MSFTN GP11.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.Seri alization;
using System.Collecti ons;

// 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 AttributeOverri des
{
public static void Main()
{
ParkingLot lot = SetupParkingLot ();
XmlTextWriter writer = new XmlTextWriter( Console.Out );
writer.Formatti ng = Formatting.Inde nted;

Console.WriteLi ne( "Writing Parking Lot Without Runtime Attributes:" );
SerializeParkin gLot( writer, lot );
Console.WriteLi ne( "" );
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.F ormatting = Formatting.Inde nted;
Console.WriteLi ne( "\n\nWritin g Parking Lot With Runtime Attributes:" );
SerializeCustom ParkingLot( anotherWriter, lot );
anotherWriter.C lose();
}

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 SerializeParkin gLot(XmlWriter writer,
ParkingLot parkingLot)
{
XmlSerializer xs = new XmlSerializer( typeof(ParkingL ot),
new Type[] { typeof(Car) } );

xs.Serialize( writer, parkingLot );
}

private static void SerializeCustom ParkingLot(XmlW riter writer,
ParkingLot parkingLot)
{
XmlAttributes carsAttributes = new XmlAttributes() ;
XmlAttributes classAttributes =
new XmlAttributes() ;

classAttributes .XmlRoot =
new XmlRootAttribut e("ParkingLotRo ot");

carsAttributes. XmlArrayItems.A dd( new
XmlArrayItemAtt ribute("ParkedC ar", typeof(Car)));

XmlAttributeOve rrides overrides =
new XmlAttributeOve rrides();

overrides.Add(t ypeof(ParkingLo t), classAttributes );
overrides.Add(t ypeof(ParkingLo t), "Cars", carsAttributes) ;

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

xs.Serialize( writer, parkingLot );
}
catch( InvalidOperatio nException )
{
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*******@hotm ail.com> wrote in message
news:uV******** ******@TK2MSFTN GP11.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. Actually, the class I'm serializing is two steps down in the inheritance ladder. It's got a parent class which also has a parent class :( All those classes in the hierarchy are Xml Serializable, and I'd think that it should be obvious that all...
2
3299
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 ‘DataItem’ public class DataItem { public DataItem() {}
0
1332
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 an error when serializing. Can this be made without redeclaring the ArrayList special attributes? The problem is that the class B is in different namespace!
4
2732
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 am using to create a sample XML file. I am trying to dimension the ArrayOfJudgeEntity to have two sets of the JudgeTableEntity values. When I run the code I get an error that the XML is not correct. I jsut can't get my head around the array...
1
2088
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 created a couple of objects and serializing it into XML based upon the schema works perfectly. The XML / Schema looks something like this:
10
8311
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) This way I have to write another "serializing" function for every new kind of struct I want to write, though. Is there a way to write functions that can write/read any struct to/from plain text format in a portable way?
2
3520
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: + More ways to contact me __________________________________________________________________
8
1399
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 reference each other. Here's my question: can I serialize Class1 and use the serialized XML in Class2? How would Class2 de-serialize the XML to retrieve the Class1's properties? I don't see how I can do this since Project2 doesn't even know about...
2
1341
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 a class called Point which has 2 variables X and Y. I save a few jobs (by serializing), and then enhance my application by adding a Z variable. How will serializing behave when loading those jobs that were created before Z was added?
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 UserControl are like that). When serializing, how could I ignore all the properties coming from the UserControl class? I know there is XmlIgnoreAttribute, but how could I set it to every property of UserControl, as it is not my class? Thank you...
0
9564
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
9387
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
10002
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...
1
9938
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8822
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...
0
6643
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3917
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
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.