1

Using XmlSerializer from .Net 4, I am trying to serialize a class that contains two classes with the same name, but different namespace.

[XmlInclude(typeof(MyNamespace1.MyClass))]
[XmlInclude(typeof(MyNamespace2.MyClass))]
public class SuperInfo
{
    public MyNamespace1.MyClass A{ get; set; }
    public MyNamespace2.MyClass B{ get; set; }
}

It turned out that the serializer could not distinguish between these 2 classes I had with the same name. The exception shows:

'Types MyNamespace1.MyClass' and 'MyNamespace2.MyClass' both use the XML type name, 'MyClass', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.

I found a solution in this thread, consisting in decorate the homonymous classes with attributes like this:

[XmlType("BaseNamespace1.MyClass")]
[XmlType("BaseNamespace2.MyClass")]

but I'm not allowed to do that, because in my case, those classes come from an automatic generated proxy to a web service.

Do you have a solution?

Community
  • 1
  • 1
javi
  • 74
  • 1
  • 7

3 Answers3

3

You can try Newtonsoft.Json to convert object to XML like below

using System.Xml.Serialization;
using Newtonsoft.Json;

namespace SoTestConsole
{
    [XmlInclude(typeof(TestClassLibrary.Class1))]
    [XmlInclude(typeof(TestClassLibrary1.Class1))]
    public class SuperInfo
    {
        public TestClassLibrary.Class1 A { get; set; }
        public TestClassLibrary1.Class1 B { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var obj = new SuperInfo()
            {
                A = new TestClassLibrary.Class1() { MyProperty = "test1" },
                B = new TestClassLibrary1.Class1() { MyProperty = "test2" }
            };

            // Error case
            //XmlSerializer xmlSerializer = new XmlSerializer(typeof(SuperInfo));

            // but below will work 
            var json = JsonConvert.SerializeObject(obj);
            var xDoc = JsonConvert.DeserializeXNode(json, "SuperInfo");

        }
    }
}

Output

<SuperInfo>
  <A>
    <MyProperty>test1</MyProperty>
  </A>
  <B>
    <MyProperty>test2</MyProperty>
  </B>
</SuperInfo>
Damith
  • 62,401
  • 13
  • 102
  • 153
1

I think you can create a partial class for each of those proxy classes and add the XmlType header in each one.

Pablo Castilla
  • 2,723
  • 2
  • 28
  • 33
  • What if I have enum types in those proxy classes? – javi May 13 '13 at 07:07
  • After having lost enough time for me, I can end with this saying that It's (almost) impossible (nothing is impossible). I tried also with the ISerializable interface implementation. – javi May 13 '13 at 11:30
0

After having lost enough time for me, I can end with this saying that It's (almost) impossible (nothing is impossible). I tried also with the ISerializable interface implementation.

javi
  • 74
  • 1
  • 7