C#XMLSerializer抽象继承类型

时间:2011-07-30 15:29:07

标签: c# xml exception serialization abstract

我遇到了来自C#的XML序列化问题。

我的课程:

public abstract class AbstractFeldtyp
{
    private string _name;
    private string _beschreibung;
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _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()};
    }
}

现在我想将“My_Root”序列化为XML文件。

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;
    }

当然,它有效。但我不知道在编译时有哪些类......

我想要一个看起来像这样的XML文件:

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

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

我不需要“Feldtyp_AB”中的属性。这种类型就足够了。感谢您的帮助:)

0 个答案:

没有答案