CaffGeek
CaffGeek

Reputation: 22064

How to remove root element of list when serializing with DataContracts

I have this class

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

It's the response type for a method in my service.

I end up with xml that looks like this:

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

But I do not want the plural InsertLoanResponses root node, I want it to look like this:

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

Upvotes: 2

Views: 1306

Answers (2)

Squiggle
Squiggle

Reputation: 2597

Perhaps change your class rather than your serializer.

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

This way you will not get a nested property when serializing.

Upvotes: 1

mikesigs
mikesigs

Reputation: 11420

You'll probably need to define a custom MessageContract for this operation. Check out the following link, specifically the section on "Using Arrays Inside Message Contracts" and the MessageHeaderArrayAttribute.

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

Upvotes: 0

Related Questions