gpt4 book ai didi

c# - 如何为 List 实现设置 XmlArrayItem 元素名称?

转载 作者:IT王子 更新时间:2023-10-29 04:52:11 24 4
gpt4 key购买 nike

我想创建一个自定义的 XML 结构,如下所示:

<Hotels>
<Hotel />
</Hotels>

我已经创建了 List 的实现,以便能够执行此操作。我的代码如下:

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

因为 List 包含的类不是 Hotel 而是 HotelBasic 我的 xml 是这样的

<Hotels>
<HotelBasic />
</Hotels>

如何在不必实现 ISerializableIEnumerable 的情况下解决此问题?

最佳答案

[XmlArray("Hotels")]
[XmlArrayItem(typeof(Hotel), ElementName="Hotel")]
public HotelList[] Messages { get; set; }

应该产生:

<Hotels>
<Hotel />
<Hotel />
</Hotels>

[XmlRoot("Hotels")]
public class HotelList : IXmlSerializable
{
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}

public void ReadXml(XmlReader reader)
{
this.Hotels = XDocument.Load(reader)
.Select(h => new Hotel { Name = (string)h.Attribute("name") }
.ToList();
}

public void WriteXml(XmlWriter writer)
{
throw new NotSupportedException();
}
}

关于c# - 如何为 List<Custom> 实现设置 XmlArrayItem 元素名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8254264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com