【问题标题】:How to exclude property name in Xml serialization in web api response如何在 Web api 响应中排除 Xml 序列化中的属性名称
【发布时间】:2016-05-04 05:55:27
【问题描述】:

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

公共部分类 GetUnitResponse { [System.ServiceModel.MessageBodyMemberAttribute(Name = "GetUnitResponse", Namespace = "", Order = 0)] [System.Xml.Serialization.XmlArrayItemAttribute("Unit", IsNullable=false)] 公共单位输出[]GetUnitResponse1; 公共GetUnitResponse() { } 公共GetUnitResponse(UnitOut [] GetUnitResponse1) { this.GetUnitResponse1 = GetUnitResponse1; } }

我从 response(GetUnitResponse) 对象中获得了以下 xml

<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 应如下所示:

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

如何做到这一点?

【问题讨论】:

    标签: c# xml asp.net-web-api


    【解决方案1】:

    默认情况下,ASP.NET Web API 使用DataContractSerializer 来序列化 XML。不幸的是,此序列化程序不支持将集合序列化为未包装的元素列表。另一方面,XmlSerializer 允许更灵活的 XML 和更多的自定义。

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

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

    现在剩下的就是用[XmlElement] 属性来装饰你的字段:

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

    另外,为了更好地封装,我建议您使用属性而不是字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多