开发者

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")]
    pub开发者_如何学Golic 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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜