BENBUN Coder
BENBUN Coder

Reputation: 4881

Problem with XML serialisation and C#

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 : ParticipationClass
{
    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.

Upvotes: 1

Views: 186

Answers (3)

Simon Mourier
Simon Mourier

Reputation: 138906

Like this:

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

    [XmlAttribute]
    public string contextControlCode;

    public ParticipationClass()
    {
    }
}

Upvotes: 1

Jon
Jon

Reputation: 437376

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 {
    // ...
}

Upvotes: 2

Mikecito
Mikecito

Reputation: 2063

This may help you out:

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

Upvotes: 1

Related Questions