使用DataContracts进行序列化时如何删除列表的根元素

时间:2013-07-16 15:41:57

标签: .net list datacontractserializer

我有这个班级

[DataContract]
public class InsertLoansResponse
{
    private ProcSummary _processingSummary;
    private List<InsertLoanResponse> _items;

    [DataMember]
    public List<InsertLoanResponse> InsertLoanResponses
    {
        get { return _items ?? (_items = new List<InsertLoanResponse>()); }
        set { _items = value; }
    }

    [DataMember]
    public ProcSummary ProcessingSummary
    {
        get { return _processingSummary ?? (_processingSummary = new ProcSummary()); }
        set { _processingSummary = value; }
    }

    public void Add(InsertLoanResponse localState)
    {
        InsertLoanResponses.Add(localState);
    }

    [DataContract]
    public class ProcSummary
    {
        [DataMember(Name = "Success")]
        public int SuccessCount { get; set; }

        [DataMember(Name = "Failure")]
        public int FailureCount { get; set; }
    }
}

这是我服务中方法的响应类型。

我最终得到的xml看起来像这样:

<InsertLoansResponse>
    <InsertLoanResponses>
        <InsertLoanResponse>
        </InsertLoanResponse>
        <InsertLoanResponse>
        </InsertLoanResponse>
    </InsertLoanResponses>
    <ProcessingSummary>
        <Failure></Failure>
        <Success></Success>
    </ProcessingSummary>
<InsertLoansResponse>

但是我不想要复数InsertLoanResponses根节点,我希望它看起来像这样:

<InsertLoansResponse>
    <InsertLoanResponse>
    </InsertLoanResponse>
    <InsertLoanResponse>
    </InsertLoanResponse>
    <ProcessingSummary>
        <Failure></Failure>
        <Success></Success>
    </ProcessingSummary>
<InsertLoansResponse>

2 个答案:

答案 0 :(得分:1)

也许改变你的课而不是你的序列化。

[DataContract]
public class InsertLoansResponse : List<InsertLoanResponse>
{
   private ProcSummary _processingSummary;
   private List<InsertLoanResponse> _items;

   // and remove the Add method, as this is now implicit to the class
}

这样,序列化时不会得到嵌套属性。

答案 1 :(得分:0)

您可能需要为此操作定义自定义MessageContract。请查看以下链接,特别是“在消息合同中使用数组”和MessageHeaderArrayAttribute。

http://msdn.microsoft.com/en-us/library/ms730255.aspx