Skip to main content
 首页 » 编程设计

c#之如何在 Web API 响应中排除 Xml 序列化中的属性名称

2024年05月10日47artech

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

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> 

客户希望排除 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> 

如何实现?

请您参考如下方法:

默认情况下,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; 
 
    ... 
} 

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