如何在XmlArray中订购XMLElements?

时间:2014-08-26 00:48:08

标签: c# xml xml-serialization

我想知道如何在XmlArray中订购XmlElement。例如,我希望Car1成为XmlArray Cars下面的第一个项目,Car2成为第二项。我已经尝试了[XmlElement("Car1", Order = 1)][XmlElement("Car1", Order = 3)],但都没有效果。这样做的正确方法是什么?

谢谢!

[XmlRoot("Items")]
public class Items
{
    [XmlElement("Owner", Order = 1)]
    public String Owner { get; set; }
    [XmlArray("Cars", Order = 2)]
    [XmlArrayItem("Car")]
    public List<Car> carList = new List<Car>();
}

public class Car
{
    [XmlElement("Car1")] // Order = 1 within "Car"
    public String Car1{ get; set; }
    [XmlElement("Car2")] // // Order = 2 within "Car"
    public String Car2{ get; set; }
}

1 个答案:

答案 0 :(得分:0)

这里你必须改变类结构

 [XmlRoot("Items")]
public class Items
{
    [XmlElement("Owner", Order = 1)]
    public String Owner { get; set; }

      [XmlArray("Cars", Order = 2)]
      public Car[] carList { get; set; }
}


public class Car
{

    [XmlElement("Car1")] // Order = 1 within "Car"
    public String Car1 { get; set; }
    [XmlElement("Car2")] // // Order = 2 within "Car"
    public String Car2 { get; set; }
}

然后使用如下代码。

Car c = new Car { Car1 = "c1", Car2 = "c2" };


Items item = new Items { Owner = "test", carList = new Car[] { c} };

输出: output