简体   繁体   中英

Conditionally Serialize XML in C# Based on Attribute

I have an XML file which I need to serialize into C# objects. Ordinarily, the XML tags dictate which object the file is serialized into. However, one of the files which I must handle uses an attribute in the XML tag called type to specify the object. 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?

Many thanks in advance

Check out another StackOverflow question: XML Deserialization - convert attribute value into class automatically (.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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