简体   繁体   中英

How to exclude property name in Xml serialization in web api response

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 the XmlSerializer allows for more flexible XML and more customizations.

You could instruct ASP.NET Web API to use XmlSerializer instead of the default one:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

And now all that's left is to decorate your field with the [XmlElement] attribute:

public partial class GetUnitResponse
{
    [XmlElement("Unit")]
    public UnitOut[] GetUnitResponse1;

    ...
}

Also for better encapsulation I would recommend you using a property instead of a field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM