序列化用XmlRoot修饰的类,在List中使用时出错

时间:2011-01-08 14:28:46

标签: c# serialization xml-serialization xmlroot

当我尝试序列化Test类型的类元素时,它给出了一个带有根元素的xml作为“testing”,它是使用XmlRoot设置的。

但是当我尝试序列化Elems类的元素时,Test元素被序列化为根元素“Test”而不是“testing”。

[XmlRoot("testing")]
public class Test
{
}

public class Elems
{
   public List<Test> how = new List<Test>();

    public Elems()
    {
        how.Add(new Test());
        how.Add(new Test());
        how.Add(new Test());
    }
}

这是Elems序列化时的输出,

<Elems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x
mlns:xsd="http://www.w3.org/2001/XMLSchema">
  <how>
    <Test />
    <Test />
    <Test />
  </how>
</Elems>

而这正是我所需要的。

<Elems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x
mlns:xsd="http://www.w3.org/2001/XMLSchema">
  <how>
    <testing />
    <testing />
    <testing />
  </how>
</Elems>

由于

1 个答案:

答案 0 :(得分:3)

试试这样:

public class Test { }

public class Elems
{
    public Elems()
    {
        How = new List<Test>();
        How.Add(new Test());
        How.Add(new Test());
        How.Add(new Test());
    }

    [XmlArray("how")]
    [XmlArrayItem("testing")]
    public List<Test> How { get; set; }
}

class Program
{
    static void Main()
    {
        var elems = new Elems();
        var serializer = new XmlSerializer(elems.GetType());
        serializer.Serialize(Console.Out, elems);
    }
}