开发者

Problem with XML serialisation and C#

开发者 https://www.devze.com 2023-03-05 23:39 出处:网络
I am trying to serialise some C# classes to XML. Things were going fine until I tried to introduce some inherited classes.

I am trying to serialise some C# classes to XML. Things were going fine until I tried to introduce some inherited classes.

The classes are [edited for size]

public class ParticipationClass
{
    [XmlAttribute]
    public string typeCode;

    [XmlAttribute]
    public string contextControlCode;

    public ParticipationClass()
    {
    }
}


public class p_recordTarget : Participati开发者_Python百科onClass
{
    public p_recordTarget()
    {
        typeCode = "RCT";
        contextControlCode = "OP";
    }
}

when using the classes the following code is used :

public class Test
{

    // other class attributes excluded.. 

    [XmlElement]
    public ParticipationClass recordTarget;

    private void Test()
    {
        recordTarget = new p_recordTarget();
    }
}

The serialisation fails with an InvalidOperationException, looking in the exception detail I can see "Message="The type itk.cda.cdaclasses.p_recordTarget was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

So I guess I need an XmlInclude, but I am not sure how.


In a nutshell, you need to use the attribute on the base class to let the serializer know about the derived classes:

[XmlInclude(typeof(p_recordTarget))]
public class ParticipationClass {
    // ...
}


This may help you out:

http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx


Like this:

[XmlInclude(typeof(p_recordTarget))]
public class ParticipationClass
{
    [XmlAttribute]
    public string typeCode;

    [XmlAttribute]
    public string contextControlCode;

    public ParticipationClass()
    {
    }
}
0

精彩评论

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