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?

4

3 回答 3

3

您可以尝试Newtonsoft.Json将对象转换为 XML,如下所示

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");

        }
    }
}

输出

<SuperInfo>
  <A>
    <MyProperty>test1</MyProperty>
  </A>
  <B>
    <MyProperty>test2</MyProperty>
  </B>
</SuperInfo>
于 2013-05-09T16:09:24.303 回答
1

我认为您可以为每个代理类创建一个部分类,并在每个代理类中添加 XmlType 标头。

于 2013-05-10T07:36:37.140 回答
0

在为我浪费了足够的时间之后,我可以用这句话结束,这(几乎)不可能(没有什么是不可能的)。我也尝试了 ISerializable 接口实现。

于 2016-09-27T11:11:50.230 回答