How do I work around the XmlSerialization problem with type name aliases (in .NET)?

I have a set of objects, and for each object, I have its type FullName and its value (as a string) or subtree of internal details (re-enter FullName and value or subtree). For each root object, I need to create a chunk of XML that will be de-serializable xml.

The problem with the XmlSerializer is that for example the following object

int age = 33;

      

will be serialized to

<int>33</int>

      

This looks ok at first, however when working with reflection you will be using System.Int32 since the type name and int is an alias and this

<System.Int32>33</System.Int32>

      

will not deserialize.

Now, the additional complexity comes from the fact that I need to handle any possible data type. So solutions using System.Activator.CreateInstance (..) and casting won't work unless I follow the code generation and compilation path as a way to achieve this (which I would rather avoid)

Notes: A quick investigation with the .NET Reflector showed that the XmlSerializer uses an inner class TypeScope , look at its static constructor to see that it initializes the inner HashTable with mappings.

So the question is, what is the best (and I mean elegant and durable) way to fool this sad fact?

+2


source to share


2 answers


I don't see exactly where your problem came from. The XmlSerializer will use the same syntax / mapping for serialization as for deserialization, so there is no conflict when used for serialization and deserialization. The type tags used are probably standard, but not sure about this. I think the problem is you are using your reflection more. Are you instantiating the imported / deserialized objects by calling Activator.CreateInstance? I would recommend the following instead, if you have some type of Foo to be generated from xml to xmlReader:

Foo DeserializedObject = (Foo)Serializer(typeof(Foo)).Deserialize(xmlReader);

      



Alternatively, if you don't want to switch to the XmlSerializer entirely, you can do some preprocessing on your input. The standard way would be to create some XSLT where you convert all of these type elements to their aliases or vice versa. then, before processing the XML, you apply your transform with System.Xml.Xsl.XslCompiledTransform and use your (or reflectors) mappings for each type.

+1


source


Why don't you serialize the entire field type as an attribute?

Instead

<age>
  <int>33</int>
</age>

      



you could do

<age type="System.Int32">
  33
</age>

      

0


source







All Articles