[英]XmlSerializer - There was an error reflecting type. Two classes with the same name
Using XmlSerializer from .Net 4, I am trying to serialize a class that contains two classes with the same name, but different namespace. 使用.Net 4中的XmlSerializer,我试图序列化一个包含两个具有相同名称但名称不同的类的类。
[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 ''. 'Types MyNamespace1.MyClass'和'MyNamespace2.MyClass'都使用来自命名空间''的XML类型名称'MyClass'。 Use XML attributes to specify a unique XML name and/or namespace for the type. 使用XML属性为类型指定唯一的XML名称和/或命名空间。
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. 但我不允许这样做,因为在我的情况下,这些类来自自动生成的代理到Web服务。
Do you have a solution? 你有解决方案吗?
You can try Newtonsoft.Json to convert object to XML like below 您可以尝试使用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");
}
}
}
Output 产量
<SuperInfo>
<A>
<MyProperty>test1</MyProperty>
</A>
<B>
<MyProperty>test2</MyProperty>
</B>
</SuperInfo>
我认为您可以为每个代理类创建一个分部类,并在每个代理类中添加XmlType标头。
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. 我也试过了ISerializable接口实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.