[英]Serialize Abstract class with different attribute name
Working on an export flow, I have a few XML elements that represent the same thing, but with a different name. 在导出流程上,我有一些XML元素表示相同的内容,但名称不同。 I can't change those names as they're defined by the other software.
我无法更改其他软件定义的名称。
I need something like that: 我需要这样的东西:
<class1>
<MY_FIELD></MY_FIELD>
</class1>
<class2>
<my_field></my_field>
</class2>
As the treatments that need to be done on both fields are the same, I wanted to create an abstract class that contains it. 由于在两个字段上需要进行的处理都是相同的,因此我想创建一个包含它的抽象类。
Right now, this is what I have: 现在,这就是我所拥有的:
public abstract class MyAbstract
{
[XmlAttribute("MY_FIELD")]
public MyField {get;set;}
}
[Serializable]
public class Class1 : MyAbstract
{
}
[Serializable]
public class Class2 : MyAbstract
{
}
Is there a way to specify a different XmlAttribute
on the final class ( class1
and class2
) so I can set the attribute on MyField
? 有没有一种方法可以在最终类(
class1
和class2
)上指定不同的XmlAttribute
,以便我可以在MyField
上设置属性?
Edit : I'm trying to use XmlAttributeOverrides
, that seems to do what I want, but I can't make it work. 编辑 :我正在尝试使用
XmlAttributeOverrides
,这似乎做我想要的,但我不能使其工作。 I don't know what I am missing. 我不知道我在想什么。
var myType = typeof(Class1);
var overrides = new XmlAttributeOverrides();
var attrs = new XmlAttributes
{
XmlAttribute = new XmlAttributeAttribute("test")
};
overrides.Add(myType, "MyField",attrs);
and for the serializer 对于串行器
var serializer = new XmlSerializer(myType, overrides);
Edit2 : Finally I end up removing the attribute on my abstract class and add a getter on each class for serialization purpose. Edit2 :最后,我最终删除了抽象类上的属性,并在每个类上添加了吸气剂以进行序列化。 It's crappy but I still hope someone can give me a proper option.
这很糟糕,但我仍然希望有人能给我适当的选择。
Try 尝试
public abstract class MyAbstract
{
abstract public MyField {get;set;}
}
[Serializable]
public class Class1 : MyAbstract
{
[XmlAttribute("MY_FIELD")]
public override MyField {get;set;}
}
[Serializable]
public class Class2 : MyAbstract
{
[XmlAttribute("my_field")]
public override MyField {get;set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.