XML 序列化:如何区分使用相同元素名称但在属性中具有不同值的类?
标题可能有点长,我解释一下我的意思。我不会向您提供我需要使用的实际 XML,但我会提供一个演示我所面临问题的 XML。
我有一个如下所示的 XML:
<root>
<creatures>
<creature type="mammal" name="lion">
<sound>roarr</sound>
</creature>
<creature type="bird" name="parrot">
<color>red</color>
</creature>
</creatures>
</root>
想象一下以下类:
(当然,这些也不是我真正的类,但您明白了。)
public class Creature
{
public string Name { get; set; }
}
public class MammalCreature : Creature
{
public string Sound { get; set; }
}
public class BirdCreature : Creature
{
public string Color { get; set; }
}
我想将 XML 序列化与属性一起使用,我希望序列化程序能够区分类型 MammalCreature
和 < code>BirdCreature 通过 type
属性。
我找到了可以通过将 xsi:type
属性设置为我想要的类型名称来实现此目的的解决方案,但我想知道是否有一个实际的解决方案可以针对我的情况执行此操作。
The title may be long, let me explain what I mean. I won't give you the actual XML that I need to work with, but I'll give one that demonstrates the issue I'm facing.
I have an XML that looks like this:
<root>
<creatures>
<creature type="mammal" name="lion">
<sound>roarr</sound>
</creature>
<creature type="bird" name="parrot">
<color>red</color>
</creature>
</creatures>
</root>
Imagine the following classes:
(Of course these are not my real classes either, but you get the point.)
public class Creature
{
public string Name { get; set; }
}
public class MammalCreature : Creature
{
public string Sound { get; set; }
}
public class BirdCreature : Creature
{
public string Color { get; set; }
}
I would like to use XML Serialization with attributes in a manner that I want the serializer to distinguish between the types MammalCreature
and BirdCreature
by the type
attribute.
I've found solutions that can do this by setting the xsi:type
attribute to the type name I want, but I'd like to know if there is an actual solution that does this for my case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不只是属性,不。然而,这段看起来毛茸茸的代码确实可以将您的 XML 正确读取到
Root
类中:Not with just attributes, no. However, this hairy looking code can indeed read your XML properly into a
Root
class:不同类型具有相同的 Xml 元素名称对您来说真的很重要吗?
如果您可以接受如下所示的 Xml,那么您最终会变得更加简单:
Is it really critical for you to have the same Xml element name for the different types?
Your can end up being much more simple if you can live with the Xml looking like that:
XML 序列化程序不支持这种情况。
The XML Serializer does not support this scenario.