XML serialization

Hi,

From the following code

public abstract class Vehicle
{
    public string licenseNumber;
}

public class Car : Vehicle
{
   public string name;
}

...

Car c= new Car();
c.licenseNumber="Lic001";
c.name= "Fiesta";

what is the simplest way to get  the following serialized XML output

<Vehicle licenceNumber="Lic001">
    <Car name="Fiesta">
    </Car>
</Vehicle>

I tried

Car c= new Car();
c.licenseNumber="Lic001";
c.name= "Fiesta";
XmlSerializer s = new XmlSerializer(typeof(Car));
StringWriter sw= new StringWriter()
s.Serialize(sw ,c);

but I get something like

<Car licenceNumber="Lic001" name="Fiesta">
</Car>

Is there some attribute I can use to get the base class to appears in the ouput

I tried xmlInclude(typeof(vehicle)) with the car class with no success.

Thanks a lot

Frederic Goulet

 


 

 

 

 

 

 




 

 



Answer this question

XML serialization

  • Aatif latif

    It looks like Vehicle is a container for car, given your desired XML output.

    Car would not derive from Vehicle, but be contained within it as a member.

    (strange OOD, eh)

     

     

     


  • TonyH

    The XmlSerializer maps "containment" to the XML hierarchy, not inheritance. So you would need to do the following to get that XML:

    public class Car : Vehicle {
    public string name;
    }

    public class Vehicle {
    public string licenseNumber;
    public Car Car;
    }


  • XML serialization