XML Deserialization - Convert attribute value to class automatically (.net)

(vb.net/c#/etc)

I am having a hard time figuring out how to do a little deserialization magic. Currently standard deserialization works fine including enums, but now I want to convert the attribute to a class. Oh! what i thought!

My xml looks something like this:

....
<review user="..." version="2.2">...</review>

      

And this is for my property / class:

[XmlAttribute("version")]
public MyVersion Version { get; set; }

class MyVersion  {
    // equality overloaded
    // can ctype() from string to MyVersion
    // constructor that takes a single string, etc
}

      

How can I help the serializer so that it can automatically deserialize my string property in this class? Do I need to modify the MyVersion class in any way or change the property definition?

  • I don't want to override any methods like OnDeserialized, etc. It's not worth it for this project.

If it is not possible to do this with the default xml deserializer, it will be good enough to know. There are many things that are not good for, so I wouldn't be surprised.

Thank!

0


source to share


2 answers


This is not supported in a declarative way. You will have to implement IXmlSerializable in the parent class (the one that is serialized to the element) and do the conversion between string and MyValue manually.



+1


source


You could do it pretty easily - just not as a deserialization action.

Use XSD to create your deserialization classes. NOw these are all partial classes, so you can write a new part of the view class (which contains the "version" attribute) and add a method that gets / sets the version.



In the get method, just create a new instance of that class, and in the set method, just update the existing version from the provided version class.

0


source







All Articles