如何设置XmlArrayItem元素名称列表<自定义>实施?自定义、如何设置、元素、名称

2023-09-04 07:15:56 作者:心为你而跳

我想创建一个自定义XML结构如下:

I want to create a custom XML structure as follows:

<Hotels>
    <Hotel />
</Hotels>

我创建列表的实施只是为了能够做到这一点。我的code是如下:

I've created an implementation of List just to be able to do this. My code is as follows:

[XmlRootAttribute(ElementName="Hotels")]
public class HotelList: List<HotelBasic>

由于该目录包含未命名类酒店,但 HotelBasic 我的XML是像

Because the class that List holds is not named Hotel but HotelBasic my xml is like

<Hotels>
   <HotelBasic />
</Hotels>

我该如何解决这个问题,而不必实施 ISerializable的的IEnumerable

推荐答案

假设你正在使用的XmlSerializer ,如果你想要做的是怎么改的 HotelBasic 类是序列化,你可以使用 XmlTypeAttribute

Assuming you are using XmlSerializer, if all you want to do is change how your HotelBasic class is serialized, you can use XmlTypeAttribute:

[XmlType(TypeName = "Hotel")]
public class HotelBasic
{
    public string Name { get; set; }
}

当你的 HotelList 类中,它将被序列为:

When used with your HotelList class it will be serialized as:

<Hotels xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Hotel>
    <Name>One</Name>
  </Hotel>
  <Hotel>
    <Name>Two</Name>
  </Hotel>
</Hotels>