views:

858

answers:

2

(vb.net/c#/etc)

I am having trouble figuring out how to do a bit of deserialization magic. Currently the standard deserialization works fine, including the enums, but now I want to convert an attribute into a class. Oh! what was I thinking!

My xml looks a bit like this:

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

And this 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 along, so that it can automatically deserialize my string property into this class? Do I need to modify the MyVersion class in some way, or change the definition of the property?

  • I do not want to have to override any methods like OnDeserialized, etc. It is not worth it for this project.

If this can't be done with the default xml deserializer, then that would be good enough to know. There are lots of things it isn't good for, so I won't be surprised.

Thanks!

+1  A: 

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

casperOne
A: 

You could do this quite easily - Just not as a deserialisation action.

Use XSD to create your classes for deserialisation. NOw these are all partial classes so you can write a new part of the review class (that contains the attribute 'version') and add a method that gets/sets the version.

In the get method simple create a new instance of that class and in the set method simple update the existing version from ther supplied version class.

Brody
Yeah, I can do this as a new property. Just trying to find a declarative (and simple) way to get around it, since I can't make that property (which NO ONE should use) private or the default serialization won't work.
Andrew Backer