When I use the XML Serializer in the following example, the first Serialize (with the class Pets) works, but the second (with the cplaa Pets2) fails. Which arrtubute nedds to be applied to make the second Serialize work
namespace SerializeTes
public class Class
[STAThread
static void Main(string[] args
Test _test = new Test()
_test.TestAnimal()
public class Tes
public void TestAnimal(
Pets newPets = new Pets()
newPets.MyCat = new Cat()
newPets.MyCat.Claws = "shapr"
newPets.MyCat.Name = "Fluffy"
newPets.MyCat.Weight = 5
newPets.MyDog = new Dog()
newPets.MyDog.Trimmed = true
newPets.MyDog.Name = "Spot"
newPets.MyDog.Weight = 10
Pets2 newPets2 = new Pets2()
newPets2.MyPet = new Cat()
((Cat)newPets2.MyPet).Claws = "Trimmed"
((Cat)newPets2.MyPet).Name = ""
((Cat)newPets2.MyPet).Weight = 6
//This will serializ
XmlTextWriter xtw = new XmlTextWriter(@"E:\Pets.xml", Encoding.UTF8)
XmlSerializer xs = new XmlSerializer(typeof(Pets))
xs.Serialize(xtw, newPets)
xtw.Close()
//This will fail with the following messag
//An unhandled exception of type 'System.InvalidOperationException' occurred in system.xml.dl
/
//Additional information: There was an error generating the XML document
/
XmlTextWriter xtw2 = new XmlTextWriter(@"E:\Pets2.xml", Encoding.UTF8)
XmlSerializer xs2 = new XmlSerializer(typeof(Pets2))
xs.Serialize(xtw2, newPets2)
xtw2.Close()
[XmlRoot
public abstract class Anima
private string _name
private int _weight
public string Nam
ge
return _name
se
_name = value
public int Weigh
ge
return _weight
se
_weight = value
public class Cat : Anima
private string _claws
public string Claw
ge
return _claws
se
_claws = value
public class Dog : Anima
private bool _trimmed
public bool Trimme
ge
return _trimmed
se
_trimmed = value
public class Pet
private Cat _myCat
private Dog _myDog
public Cat MyCa
ge
return _myCat
se
_myCat = value
public Dog MyDo
ge
return _myDog
se
_myDog = value
public class Pets
private Animal _myPet
public Animal MyPe
ge
return _myPet
se
_myPet = value