Search code examples
c#xmlservicestackservicestack-text

ServiceStack Output XML format - xml attribute


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.


Solution

  • 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);