gpt4 book ai didi

c# - 反序列化此 XML 字符串的正确方法是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 02:25:36 27 4
gpt4 key购买 nike

我将主页上显示的项目存储为 XML 字符串(在设置中)。

<?xml version=""1.0""?>
<HomePageItemList>
<PlantHomePageItem>
<Name>Plant1</Name>
</PlantHomePageItem>
<PlantHomePageItem>
<Name>Plant2</Name>
</PlantHomePageItem>
<AdminHomePageItem>
<Name>Admin1</Name>
</AdminHomePageItem>
</HomePageItemList>

有些项目代表植物 PlantHomePageItem,其他项目代表管理工具 AdminHomePageItem。两者继承相同的基类 HomePageItem

[XmlRoot("HomePageItemList")]
public class TestSerialization
{
[XmlArray("HomePageItemList")]
[XmlArrayItem("PlantHomePageItem", Type = typeof(PlantHomePageItem))]
[XmlArrayItem("AdminHomePageItem", Type = typeof(AdminHomePageItem))]
public List<HomePageItem> HomePageItemList { get; set; }
}

[XmlInclude(typeof(PlantHomePageItem))]
[XmlInclude(typeof(AdminHomePageItem))]
public class HomePageItem
{
[XmlElement("Name")]
public string Name { get; set; }
}

public class PlantHomePageItem : HomePageItem { }
public class AdminHomePageItem : HomePageItem { }

当我尝试对其进行反序列化时,我没有运行时错误,只是一个空对象...

MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
XmlSerializer xs = new XmlSerializer(typeof(TestSerialization));
TestSerialization obj = (TestSerialization)xs.Deserialize(ms);

Console.WriteLine(obj.HomePageItemList.Count);

foreach (var item in obj.HomePageItemList)
{
Console.WriteLine("{0}: {1}", item.GetType().Name, item.Name);
}

返回

0

包含完整内容的 .NET Fiddle 可用:https://dotnetfiddle.net/f51b0K

最佳答案

将您的 TestSerialization 类更改为此...

[XmlRoot("HomePageItemList")]
public class TestSerialization
{
[XmlElement("PlantHomePageItem", Type = typeof(PlantHomePageItem))]
[XmlElement("AdminHomePageItem", Type = typeof(AdminHomePageItem))]
public List<HomePageItem> HomePageItemList { get; set; }
}

Your modified example...

关于c# - 反序列化此 XML 字符串的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46359276/

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