简体   繁体   English

如何在.NET(数组)中序列化这个Xml

[英]How to serialize this Xml in .NET (array)

I need Xml that looks like this 我需要看起来像这样的Xml

<foo>
  <bar ... />
  <bar ... />
</foo>

And currently have the following class structure : 目前有以下类结构:

[XmlRoot("foo")]
public class Foo
{
  [XmlArrayItem("bar")]
  public List<Bar> myBars;
}

But this gives me Xml where bar items are wrapped inside a bars element. 但这给了我Xml,其中条形项包含在一个条形元素中。 How should I define my custom XmlAttributes so I'd get the Xml structure I need? 我应该如何定义我的自定义XmlAttributes,以便获得我需要的Xml结构?

I had to solve something similar yesterday, and this was the solution for me: 我昨天必须解决类似问题,这对我来说是解决方案:

[XmlRoot("foo")]
public class Foo
{
    [XmlElement("bar")]
    public List<Bar> myBars;
}

The solution I use is this: 我使用的解决方案是这样的:

[XmlRoot("foo")]
public class Foo : List<Bar>
{
}

[XmlType("bar")]
public class Bar
{
}

In fact, I defined Foo as a List<T> , so it works as a generic list. 事实上,我将Foo定义为List<T> ,因此它可以作为通用列表。 The type in that list just needs to define the XmlType attribute. 该列表中的类型只需要定义XmlType属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM