XML Deserialization - convert attribute value into class automatically (.net)

南笙酒味 提交于 2020-01-06 04:42:27

问题


(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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/421660/xml-deserialization-convert-attribute-value-into-class-automatically-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!