Tarak
Tarak

Reputation: 221

customize the order of displaying elements while serialization using C#

I have a class that defines the elements as below in a C# Item Class

public class Item
{       

    public string ShortDesc {get;set;}

    [XmlArrayItem(ElementName="category")]
    public List<string> categories = new List<string>();
    public string SubType{get;set;}
}

in my code behind I have this code

Item() itm = new Item();
itm.SubType = "Applications";
itm.categories.Add("Category1");
itm.categories.Add("Category2");
itm.categories.Add("Category3");
itm.ShortDesc="Short Description";

I am getting this XML output when i serialize the object

XML:

<subtype>Applications</subtype>
<shortDesc>Short Description</shortDesc>
<categories>
      <category>Category1</category>
      <category>Category2</category>
      <category>Category3</category>
</categories>

but i want the output to be in this order

<subtype>Applications</subtype>
<categories>
      <category>Category1</category>
      <category>Category2</category>
      <category>Category3</category>
</categories>
<shortDesc>Short Description</shortDesc>

how is it possible to display this way i tried with Order= but it takes only to the XMLELement

Upvotes: 1

Views: 1066

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064004

public class Item
{
    [XmlElement("shortDesc", Order=2)]
    public string ShortDesc { get; set; }

    private readonly List<string> categories = new List<string>();
    [XmlArray("categories", Order = 3), XmlArrayItem("category")]
    public List<string> Categories { get { return categories; } }

    [XmlElement("sub-type", Order = 1)]
    public string SubType { get; set; }
}

Note the explicit [XmlArray], which allows us to specify the Order=. I also moved the list into a property for you (which is the norm).

Upvotes: 4

Related Questions