Sergey Slepov
Sergey Slepov

Reputation: 2111

How to control the tag order in the xml returned by a WCF [WebGet] marked method

My WCF service method:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "decl/xml?s={s}")]
public Paradigm GetDeclensionXml(string s)
{
    return GetDeclension (s);
}

returns a custom object that has a bunch of string fields:

public class Paradigm
{
    public string genitive;
    public string dative;
    public string accusative;
    public string instrumental;
    public string prepositional;
}

that gets serialized to this XML:

<Paradigm xmlns="http://schemas.datacontract.org/2004/07/MorpherWebDemo20.ws" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <accusative>росу</accusative>
    <dative>росе</dative>
    <genitive>росы</genitive>
    <instrumental>росой</instrumental>
    <prepositional>росе</prepositional>
</Paradigm>

I.e. the tags are automaticallly ordered by name. I want them to appear in the order they are defined in my custon class. Any ideas how to achieve that?

P.S. The same happens if I change ResponseFormat to JSON.

Upvotes: 0

Views: 204

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87218

You can decorate the class with [DataContract] and the members with [DataMember], and you'll be able to use the Order property of this attribute to do what you want:

[DataContract]
public class Paradigm
{
    [DataMember(Order = 1)]
    public string genitive;
    [DataMember(Order = 2)]
    public string dative;
    [DataMember(Order = 3)]
    public string accusative;
    [DataMember(Order = 4)]
    public string instrumental;
    [DataMember(Order = 5)]
    public string prepositional;
}

Upvotes: 1

Related Questions