如何在序列化时避免使用自定义集合类的名称

时间:2013-02-26 21:17:52

标签: .net xml-serialization

我有一个自定义集合类作为另一个类的属性,如下所示:

class MyDataClass
{
    CustomCollection<MyType> DataCollection;
}

它实现了IXmlSerializable,因此可以很好地序列化。我唯一的抱怨是生成的xml看起来像这样:

<MyDataClass>
  <DataCollection>
    <MyType />
    <MyType />
  </DataCollection>
</MyDataClass>

当我不希望集合在xml中时,就像这样:

<MyDataClass>
  <MyType />
  <MyType />
</MyDataClass>

我已经读过Lists and Arrays,您可以添加[XmlElement]属性来告诉xml序列化程序将该集合呈现为一个未包装的元素列表,但这对我不起作用。

1 个答案:

答案 0 :(得分:1)

这应该有效:

public class MyDataClass
{
    [XmlElement("MyType")]
    public CustomCollection<MyType> DataCollection;

} 

public class CustomCollection<T> : List<T> { }
public class MyType { }

public static void Main()
{
    MyDataClass c = new MyDataClass();
    c.DataCollection = new CustomCollection<MyType>();
    c.DataCollection.Add(new MyType { });
    c.DataCollection.Add(new MyType { });

    XmlSerializer xsSubmit = new XmlSerializer(typeof(MyDataClass));
    StringWriter sww = new StringWriter();
    XmlWriter writer = XmlWriter.Create(sww);
    xsSubmit.Serialize(writer, c);
    var xml = sww.ToString(); // Your xml
}

结果xml看起来像

  <?xml version="1.0" encoding="utf-16" ?> 
    <MyDataClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <MyType /> 
      <MyType /> 
   </MyDataClass>