I have a class named GetUnitResponse whose definition is as follows
public partial class GetUnitResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetUnitResponse", Namespace = "", Order = 0)] [System.Xml.Serialization.XmlArrayItemAttribute("Unit", IsNullable=false)] public UnitOut[]GetUnitResponse1; public GetUnitResponse() { } public GetUnitResponse(UnitOut[] GetUnitResponse1) { this.GetUnitResponse1 = GetUnitResponse1; } }
I'm getting a following xml from the response(GetUnitResponse) object
<pre>
<GetUnitResponse xmlns:xsi="" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<GetUnitResponse1>
<Unit day="2016-01-27" ID="572">
</Unit>
<Unit day="2016-01-27" ID="573">
</Unit>
<Unit day="2016-01-27" ID="574">
</Unit>
</GetUnitResponse1>
</GetUnitResponse>
</pre>
Client wants the GetUnitResponse1 tag to be excluded and the resultant xml should be like below:
<pre>
<GetUnitResponse xmlns:xsi="" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Unit day="2016-01-27" ID="572">
</Unit>
<Unit day="2016-01-27" ID="573">
</Unit>
<Unit day="2016-01-27" ID="574">
</Unit>
</GetUnitResponse>
</pre>
How to achieve this ?
By default, ASP.NET Web API uses the
DataContractSerializer
to serialize XML. Unfortunately this serializer does not support serializing out a collection as an unwrapped list of elements. On the other hand theXmlSerializer
allows for more flexible XML and more customizations.You could instruct ASP.NET Web API to use XmlSerializer instead of the default one:
And now all that's left is to decorate your field with the
[XmlElement]
attribute:Also for better encapsulation I would recommend you using a property instead of a field.