如何以XML序列化的Web API响应排除属性名 [英] How to exclude property name in Xml serialization in web api response

查看:106
本文介绍了如何以XML序列化的Web API响应排除属性名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为GetUnitResponse其定义类如下:

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;
    }
}

我是从响应得到一个下面的XML(GetUnitResponse)对象

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>

客户希望要排除的GetUnitResponse1标签和生成的XML应该象下面这样:

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 ?

推荐答案

默认情况下,的ASP.NET Web API使用<一个href=\"https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer(v=vs.110).aspx\"相对=nofollow> 的DataContractSerializer 序列化XML。不幸的是这串不支持序列化了一个集合为元素的展开列表。另一方面在<一href=\"https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx\"相对=nofollow> 的XmlSerializer 允许更灵活的XML和更多的自定义设置。

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.

您可以指示的ASP.NET Web API,而不是使用默认的XmlSerializer的:

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

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

现在所有剩下的就是与 [的XmlElement] 属性来装饰你的领域:

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

    ...
}

也为更好的封装我会用一个属性,而不是一个领域的建议你。

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

这篇关于如何以XML序列化的Web API响应排除属性名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆