How to Ignore Non-Serializable Child When Serializing Object?

O

O.B.

I have two classes, Logger and LoggerRuntime. Logger is serializble,
LoggerRuntime is not. LoggerRuntime inherits from Logger. At runtime,
I get a list of LoggerRuntime instances to save to an XML file. I only
want the public attributes of the parent Logger class to get written to
the file. Therefore, I cast the LoggerRuntime objects to "Logger" and
then try to serialize the Logger objects. Instead, I get the following
error:

System.InvalidOperationException: The type
SerializationTest.LoggerRuntime was not expected. Use the XmlInclude or
SoapInclude attribute to specify types that are not known statically.

What am I doing wrong?
 
M

Marc Gravell

Casting doesn't matter; it still *is* a LoggerRuntime, no matter how it is
masquerading. In this case, you would probably be best to tell XmlSerializer
to expect also LoggerRuntime (there is an overload for this, or you can use
the XmlInclude attribute on Logger) - and mark the additional public
properties (in LoggerRuntime) with [XmlIgnore] to stop it from attempting to
serialize them.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top