使用C#定制序列化时显示元素的顺序

时间:2010-12-02 11:43:36

标签: c# xml-serialization

我有一个类在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;}
}

在我的代码后面我有这个代码

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

我在序列化对象时获得此XML输出

XML:

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

但我希望输出按此顺序

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

如何以Order=尝试显示这种方式,但只需XMLELement

1 个答案:

答案 0 :(得分:4)

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

请注意显式[XmlArray],这样我们就可以指定Order=。我还将列表移动到您的属性(这是常态)。