How can I make DataContractSerializer XML more readable?


  • I want to serialize a complex data structure to XML.

    Objects have lists / dictionaries of other objects that might have lists / dictionaries of other objects themselves.

    Generally I'd just use the DataContractSerializer but it produces ugly, hard to read XML with weird clutter, some XML tags have arbitrary characters after them (KeyValueOfstringChildB5f9yUGrh) and if you remove that clutter the XML is no longer recognized by the DataContractSerializer.

    I tried using an XMLSerializer instead but it cannot serialize dictionaries for whatever reason.

    How can I create an easily readable XML serialization of complex classes with dictionaries?

    Whether it's "fixing" the  DataContractSerializer's XML or making it possible to serialize dictionaries with the XMLSerializer.

    Tuesday, March 28, 2017 12:42 PM

All replies

  • You'll get the ugly names whenever you're using multiple generic types because the generator cannot generate something like Key<string> and having multiple ones would conflict. If you want cleaner names then create derived types for your generics. That should resolve the issue but, of course, adds redundant types that are just for serialization.

    Serialization isn't really designed to be pretty and readable. It's designed to get data back and forth. You can use attributes (eg. DataMember) to control some of the naming to make it more readable so I'd start with that. If that doesn't get you where you want then you might just need to implement the necessary interface(s) to serialize the data yourself and forego data contracts. The XML formatting would need to be pretty important to "waste" time doing that though.

    Michael Taylor

    Tuesday, March 28, 2017 1:57 PM