1

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.

1

3 Answers 3

2

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 {
    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick answer. I have tried this and it does not seem to make any difference. Looking at Simon's answer (which is the same) and other web resources I suspect this should be the answer. But it still does not work, and yields the same exception.
1

This may help you out:

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

Comments

1

Like this:

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

    [XmlAttribute]
    public string contextControlCode;

    public ParticipationClass()
    {
    }
}

2 Comments

Simon, see the comments I made to Jon ( who had the same answer ). I think it should work but it does not appear to.
I think you can also put it on the method, but I should have the same effet. Or It's a cache issue. Serialization is cached (whenever possible).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.