marek
marek

Reputation: 120

C# XML serialization of generic property

I have following classes:

public class Response<T>
{ 
  public string Status { get; set; }
  public T GenericType { get; set; }
}
public class Order
{
  public string Number { get; set; }
}
public class Customer
{
  public string Name { get; set; }
}

and would like to get for:

var r = new Response<Order>();
r.GenericType = new Order { Number = "1" };

following xml after serialization:

<Response><Order><Number>1</Number></Order></Response>

and for:

var r = new Response<Customer>();
r.GenericType = new Customer { Name = "Kowalski" };

following xml after serialization:

<Response><Customer><Name>Kowalski</Name></Customer></Response>

Is it possible?

Thanks a lot.

Marek

Upvotes: 3

Views: 1040

Answers (2)

marek
marek

Reputation: 120

Thanks Pieter for your answer.

Yes, I implemented the IXmlSerializable interface and WriteXml method of my Reponse object looks following:

public void WriteXml(XmlWriter writer)
{
    writer.WriteRaw(string.Format("<Status>{0}</Status>", Status));
    var xml = GenericType.Serialize();
    writer.WriteRaw(xml);
}

The Serialize() extension is a generic method, which serializes any object.

Thanks,

Marek

Upvotes: 0

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29640

You can use IXmlSerializable to override how the XmlSerializer works.

That way, you can get the output you're looking for.

Upvotes: 4

Related Questions