Why is XmlSerializer so hard to use?

Posted by mafutrct on Stack Overflow See other posts from Stack Overflow or by mafutrct
Published on 2010-03-23T15:46:09Z Indexed on 2010/03/23 15:53 UTC
Read the original article Hit count: 419

Filed under:
|

I imagine to use XML serialization like this:

class Foo {
    public Foo (string name) {
        Name1 = name;
        Name2 = name;
    }

    [XmlInclude]
    public string Name1 { get; private set; }

    [XmlInclude]
    private string Name2;
}

StreamWriter wr = new StreamWriter("path.xml");
new XmlSerializer<Foo>().Serialize (wr, new Foo ("me"));

But this does not work at all:

  • XmlSerializer is not generic. I have to cast from and to object on (de)serialization.
  • Every property has to be fully public. Why aren't we just using Reflection to access private setters?
  • Private fields cannot be serialized. I'd like to decorate private fields with an attribute to have XmlSerializer include them.

Did I miss something and XmlSerializer is actually offering the described possibilities? Are there alternate serializers to XML that handle these cases more sophisticatedly?

If not: We're in 2010 after all, and .NET has been around for many years. XML serialization is often used, totally standard and should be really easy to perform. Or is my understanding possibly wrong and XML serialization ought not to expose the described features for a good reason?

(Feel free to adjust caption or tags. If this should be CW, please just drop a note.)

© Stack Overflow or respective owner

Related posts about c#

Related posts about xmlserializer