开发者

C# XMLSerialize abstract inherited type

开发者 https://www.devze.com 2023-03-24 04:42 出处:网络
I have a problem with the XML serialization from C#. My classes: public abstract class AbstractFeldtyp {

I have a problem with the XML serialization from C#.

My classes:

public abstract class AbstractFeldtyp
{
    private string _name;
    private string _beschreibung;
    public string Name
    {
        get
        {
            return _name;
        }
        set
       开发者_JAVA技巧 {
            _name = value;
        }
    }

    public string Beschreibung
    {
        get
        {
            return _beschreibung;
        }
        set
        {
            _beschreibung = value;
        }
    }
}

public class Feldtyp_A : AbstractFeldtyp {
    public Feldtyp_A() {
        Name = "My name is A";
        Beschreibung = "I'm a A";
    }
}

public class Feldtyp_B : AbstractFeldtyp {
    public Feldtyp_B() {
        Name = "My name is B";
        Beschreibung = "I'm not a A!";
    }
}

public class My_Root {
    private AbstractFeldtyp[] felder;

    public My_Root() {
        Name = "My name is B";
        Beschreibung = "I'm not a A!";
        felder = new AbstractFeldtyp[] { new Feldtyp_A(), new Feldtyp_B()};
    }
}

Now I want to serialize "My_Root" to a XML-File.

public class Serializer
{
    private XmlSerializer s;
    private FileStream stream;
    public Serializer()
    {
        /* This is not acceptable! I must be dynamically */
        Type[] t = new Type[]
        {
            typeof(Feldtyp_A),
            typeof(Feldtyp_B)
        };
        /* End */

        s = new XmlSerializer(typeof(My_Root), t);

        AbstractMaschinenTyp m = new MaschineTyp1();
        this.SerializeObject(m);
    }

    public void SerializeObject(object obj)
    {
        stream = new FileStream(@"D:\File.xml", FileMode.Create);
        if(obj != null)
            s.Serialize(stream, obj);
        stream.Close();
    }

    public object DeserializeObject()
    {
        stream = new FileStream(@"D:\File.xml", FileMode.Open);
        object o = s.Deserialize(stream);
        stream.Close();
        return o;
    }

Sure, it works. But i dont know at compile-time what classes are there...

I want a XML-File that looks like:

<?xml version="1.0"?>
<My_Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Felder>
        <Feld>
            <Feldtyp type="Feldtyp_A" />
        </Feld>
        <Feld>
            <Feldtyp type="Feldtyp_B" />
        </Feld>
    </Felder>
</My_Root>

or

<?xml version="1.0"?>
<My_Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Felder>
        <Feldtyp type="Feldtyp_A" />
        <Feldtyp type="Feldtyp_B" />
    </Felder>
</My_Root>

I do not need the properties from "Feldtyp_AB". The the type is enough. Thanks for help :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号