0

I have a custom class that only has one property of type string.

Attempting to serialise an object of this class as an attribute using XmlSerializer results in the exception:

XmlAttribute/XmlText cannot be used to encode complex types

Now I know I can fudge this my creating a pseudo string property in my containing type and serialising that instead, but is there any way at all to make my custom class support it intrinsically?

How do .Net classes do it (eg DateTime)?

GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103

1 Answers1

1

In order to this you have to implement IXmlSerializable and fully control how your type is serialized / deserialized. Rather overwhelming effort for such an easy task, though. People mostly get stuck with this when it comes to Nullable types.

empi
  • 15,755
  • 8
  • 62
  • 78
  • 2
    Are you sure this will work? How does .Net know that I won't try and serialise one or more xml elements in my implementation? – GazTheDestroyer May 01 '12 at 09:09
  • You are in control of serialization so you are able to say what to write http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.writexml.aspx – empi May 01 '12 at 09:26
  • I know I can say, but .Net does not know what I'm going to do, so it doesn't know whether my class can be contained in an attribute. My question is how do I tell .Net that I can be serialised to an attribute. – GazTheDestroyer May 01 '12 at 09:35
  • Could you give an example what do you want to achieve? Have you tried implementing IXmlSerializable? – empi May 01 '12 at 14:29