简体   繁体   中英

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. 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 ?

Edit : I'm trying to use XmlAttributeOverrides , that seems to do what I want, but I can't make it work. 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. 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;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM