2

I am using ServiceStack and need to render XML in specific format.

Here is my POCO class

[DataContract]
public class LookupModelBase
{
    [XmlAttribute, DataMember]
    public int Id { get; set; }

    [XmlText, DataMember]
    public string Label { get; set; }
}

And expected output should be like below.

<LookupModelBase Id="1">
   <Label>Label 1</Label>
</LookupModelBase>

However I am getting output like below

<LookupModelBase>
   <Id>1</Id>
   <Label>Label 1</Label>
</LookupModelBase>

How can I fix this issue.

Mehmet Otkun
  • 1,374
  • 9
  • 22

2 Answers2

0

ServiceStack uses .NETs XML DataContractSerializer which only allows customization via .NETs DataContract attributes, not the XmlSerializer attributes you’re also using.

mythz
  • 141,670
  • 29
  • 246
  • 390
  • How can I configure like this link https://stackoverflow.com/questions/13493594/how-can-i-override-the-xml-serialization-format-on-a-type-by-type-basis-in-servi/13498725#13498725 – Mehmet Otkun Mar 10 '18 at 13:27
  • @MehmetOtkun you can override the default XML Serializer via the ContentTypes API as per the example at the bottom of the question. – mythz Mar 10 '18 at 13:39
0

I solved,

public static class CustomServiceStackXmlFormat
{
    public static string Format = "application/xml";

    public static void Serialize(IRequest req, object response, Stream stream)
    {
        System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(response.GetType());
        xmlSerializer.Serialize(stream, response);
    }

    public static object Deserialize(Type type, Stream stream)
    {
        System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type.GetType());
        var obj = ((Type)xmlSerializer.Deserialize(stream));
        return obj;
    }
}

In your AppHost.cs

this.ContentTypes.Register(CustomServiceStackXmlFormat.Format, CustomServiceStackXmlFormat.Serialize, CustomServiceStackXmlFormat.Deserialize);
Mehmet Otkun
  • 1,374
  • 9
  • 22