简体   繁体   English

基于属性在C#中有条件地序列化XML

[英]Conditionally Serialize XML in C# Based on Attribute

I have an XML file which I need to serialize into C# objects. 我有一个XML文件,需要将其序列化为C#对象。 Ordinarily, the XML tags dictate which object the file is serialized into. 通常,XML标记指示文件要序列化到的对象。 However, one of the files which I must handle uses an attribute in the XML tag called type to specify the object. 但是,我必须处理的文件之一使用XML标记中的属性type来指定对象。 For example, see the code below. 例如,请参见下面的代码。

<library>
  <item type="book">Great Expectations</item>
  <item type="magazine">National Geographic</item>
  <item type="cd">Blue Valentines</item>
</library>

Is it possible to use XML serialization attributes such that each item will serialize into an object whose type is specified by the type attribute in the XML, ie Great Expectations will serialize into a book object, etc? 是否可以使用XML序列化属性,以便将每个项目序列化为一个对象,该对象的类型由XML中的type属性指定,即,Great Expectations将序列化为book对象,等等?

Many thanks in advance 提前谢谢了

Check out another StackOverflow question: XML Deserialization - convert attribute value into class automatically (.net) . 看看另一个StackOverflow问题: XML反序列化-将属性值自动转换为类(.net)

Deserializing an array item into a specific type doesn't appear to be supported by the attributes alone. 将数组项反序列化为特定类型似乎并不仅仅受属性支持。 You will need to implement a custom IXmlSerializable. 您将需要实现一个定制的IXmlSerializable。

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

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