XML 反序列化 - 自动将属性值转换为类 (.net) [英] XML Deserialization - convert attribute value into class automatically (.net)

查看:34
本文介绍了XML 反序列化 - 自动将属性值转换为类 (.net)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(vb.net/c#/etc)

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

我的 xml 看起来有点像这样:

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
}

我如何帮助序列化程序,以便它可以自动将我的字符串属性反序列化为此类?我是否需要以某种方式修改 MyVersion 类,或者更改属性的定义?

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?

  • 不想必须覆盖任何方法,例如 OnDeserialized 等.对于这个项目来说,这不值得.
  • I do not want to have to override any methods like OnDeserialized, etc. It is not worth it for this project.

如果使用默认的 xml 反序列化器无法做到这一点,那么知道这一点就足够了.它有很多不适合的地方,所以我不会感到惊讶.

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.

谢谢!

推荐答案

这在声明性方式中不受支持.您必须在父类(序列化为元素的类)上实现 IXmlSerializable 并手动执行字符串和 MyValue 类型之间的转换.

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.

这篇关于XML 反序列化 - 自动将属性值转换为类 (.net)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆