2

I have a class that has a fairly simple string representation. Serializing and deserializing to and from this string is not difficult.

What I would like to be able to do is use an XmlAttribute like so:

public class MyClass
{

     [XmlAttribute("MyValue")]
     public MySubClass {get; set;}

}

So that MySubClass, whenever it's serialized, can appear as an attribute:

<Myclass MyValue="XXYYZZ">
// other stuff omitted
</MyClass>

I'm currently attempting to use IXmlSerializable in MySubClass, but I get this serialization exception:

XmlAttribute/XmlText cannot be used to encode types implementing IXmlSerializable."

I know this is possible because it works with DateTime. I've looked at the source code for DateTime and I see that ISerializable is implemented, but thats for binary serialization. I also see IFormattable implemented, but I don't know if that's the trick.

Question: how can I make a class that behaves just like DateTime when it comes to xml serialization within xml attributes?

Charlie Salts
  • 13,109
  • 7
  • 49
  • 78
  • How do you get "XXYYZZ" from an instance of `MySubClass`? Perhaps just overriding the `ToString` method on `MySubClass` will do it. – Chris Dunaway Jun 22 '15 at 18:39
  • How I get the string depends on how I serialize it. If I use IXmlSerializable, then it's in the ReadXml and WriteXml functions. I do have a ToString function but serializing the class still generates the exception message "XmlAttribute/XmlText cannot be used to encode complex types." – Charlie Salts Jun 22 '15 at 18:54
  • I meant that when you want to serialize the `MySubClass` instance, do you always want the value of a particular property of that class or is it derived from several properties? Perhaps you can make that property not serializable (using `XmlIgnore`) and then create another one where the getter returns the value that you want serialized. – Chris Dunaway Jun 22 '15 at 20:27
  • Think of MySubClass as being like a string or an int or datetime - it's just a single value that can be represented as a string, and parsed back again. – Charlie Salts Jun 22 '15 at 22:18
  • 1
    I don't want to use the XmlIgnore trick because I want to use this in a bunch of places and I don't want duplicate properties everywhere. I just want a class that behaves like `DateTime`. – Charlie Salts Jun 22 '15 at 22:19
  • Unfortunately the magic is not inside the DateTime class, the XmlSerializer itself has special codepaths for DateTime. – HugoRune Feb 24 '17 at 11:25

0 Answers0