2

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

class MyDataClass
{
    CustomCollection<MyType> DataCollection;
}

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

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

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

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

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

4

1 回答 1

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>
于 2013-02-26T21:34:56.793 回答