C # XML serialization of a generic property

I have the 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 receive for:

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

after xml after serialization:

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

and for:

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

after xml after serialization:

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

Is it possible?

Many thanks.

Marek

+3
source share
2 answers

You can use IXmlSerializableto override how it works XmlSerializer.

This way you can get the result you are looking for.

+4
source

Thanks Pieter for your reply.

Yes, I implemented an interface IXmlSerializableand WriteXmlmy object is Reponseas follows:

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

Extension Serialize()is a general method that serializes any object.

Thank,

Marek

0
source

Source: https://habr.com/ru/post/1789763/


All Articles