I have an classic object model, base class with two or moresubclasses. When I know exactly that there is only these twoclasses then I have no problem serilaising and deserialsing theinstances. However, my new requirement concerns a pluginarchitecture that loads subclasses that are only known atruntime. The first hurdle of reading these differing subclassesfrom a configuration file was relatively trivial, although Ithought it would be my biggest are of concern. However, theserialising of these instances is proving to be a headache (andI thought it would be the easier part). Basic structure is aclass containing an ArrayList that, in turn, contains each ofthe instances of the subclass.
Given the ParkingLot example from TopXML (a superb XML IMHO) mychanges are:
private static ParkingLot SetupParkingLot()
{
ParkingLot lot = new ParkingLot();
lot.Vehicles = new ArrayList();
Car wifesCar = new Car();
wifesCar.Make = "Ford";
wifesCar.Model = "Explorer";
wifesCar.Year = 1997;
wifesCar.VIN = "ABC123DEF";
Car myCar = new Car();
myCar.Make = "Mercedes Benz";
myCar.Model = "SLK500";
myCar.Year = 2005;
myCar.VIN = "ABC123DEF";
Motorcycle neighborsToy = new Motorcycle();
neighborsToy.Make = "Ducati";
neighborsToy.Model = "Monster";
neighborsToy.Year = 1995;
neighborsToy.VeryLoud = true;
lot.Vehicles.Add( wifesCar );
lot.Vehicles.Add( myCar );
lot.Vehicles.Add( neighborsToy );
return lot;
}
and
private static void SerializeCustomParkingLot(XmlWriterwriter,
ParkingLot parkingLot)
{
XmlAttributes carsAttributes = new XmlAttributes();
XmlAttributes classAttributes =
new XmlAttributes();
classAttributes.XmlRoot =
new XmlRootAttribute("ParkingLotRoot");
carsAttributes.XmlArrayItems.Add( new
XmlArrayItemAttribute("ACar", typeof(Car)));
carsAttributes.XmlArrayItems.Add( new
XmlArrayItemAttribute("AMotorcycle", typeof(Motorcycle)));
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 ex )
{
System.Console.WriteLine( "Bad override attributes" );
}
}
Trouble is I will always receive the InvalidOperationExceptionwith an inner exception of
The type Car was not expected. Use the XmlInclude or SoapIncludeattribute to specify types that are not known statically.
Could anybody please shed some light on this?
--------------------------------
From: Graham McDonald
-----------------------
Posted by a user from .NET 247 (http://www.dotnet247.com/)
<Id>4rOzxcdD1UWXcqK03uMyOw==</Id>