c# - How to exclude property name in Xml serialization in web api response -


i have class named getunitresponse definition 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 following xml 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 getunitresponse1 tag excluded , resultant xml should 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 achieve ?

by default, asp.net web api uses datacontractserializer serialize xml. unfortunately serializer not support serializing out collection unwrapped list of elements. on other hand xmlserializer allows more flexible xml , more customizations.

you instruct asp.net web api use xmlserializer instead of default one:

globalconfiguration.configuration.formatters.xmlformatter.usexmlserializer = true; 

and that's left decorate field [xmlelement] attribute:

public partial class getunitresponse {     [xmlelement("unit")]     public unitout[] getunitresponse1;      ... } 

also better encapsulation recommend using property instead of field.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -