C# XML序列化错误:两个类型都使用XML类型名称&x27;关系';,从名称空间'';
我在通过XML序列化时遇到了一个问题,因为两个类使用了一个名为Relationship的类(尽管不同的类!)。我已尝试使用XML属性用另一个名称装饰其中的1个类,但它仍然会出现以下错误: {“类型'SiteServer.Relationship'和'LocalServer.Relationship'都使用来自命名空间''的XML类型名称'Relationship'。使用XML属性为该类型指定唯一的XML名称和/或命名空间。“} 这是我的两门课,有人知道为什么吗??我是否使用了错误的属性?它似乎忽略了它:-)C# XML序列化错误:两个类型都使用XML类型名称&x27;关系';,从名称空间'';,c#,xml,exception-handling,xml-serialization,C#,Xml,Exception Handling,Xml Serialization,我在通过XML序列化时遇到了一个问题,因为两个类使用了一个名为Relationship的类(尽管不同的类!)。我已尝试使用XML属性用另一个名称装饰其中的1个类,但它仍然会出现以下错误: {“类型'SiteServer.Relationship'和'LocalServer.Relationship'都使用来自命名空间''的XML类型名称'Relationship'。使用XML属性为该类型指定唯一的XML名称和/或命名空间。“} 这是我的两门课,有人知道为什么吗??我是否使用了错误的属性?它似乎忽
用XmlRoot装饰您的两个类,如下所示:
[XmlRoot("SiteServer", Namespace="http://example.com/schemas/SiteServer")]
public class SiteServer
{
[XmlRoot("SiteServerRelationShip", Namespace="http://example.com/schemas/SiteServer")]
public class Relationship
{
public string type { get; set; }
}
public string Name { get; set; }
public Relationship Relate = new Relationship();
}
[XmlRoot("LocalServer", Namespace="http://example.com/schemas/LocalServer")]
public class LocalServer
{
[XmlRoot("LocalServerRelationship", Namespace="http://example.com/schemas/LocalServer")]
public class Relationship
{
public string type { get; set; }
}
public string Name { get; set; }
public Relationship Relate = new Relationship();
}
这将为两个关系类生成两个不同的FQDN:
{http://example.com/schemas/LocalServer}LocalServerRelationShip
{http://example.com/schemas/SiteServer}SiteServerRelationShip
您还必须装饰场地,例如:
[XmlInclude(typeof(Relationship))]
public class SiteServer
{
[XmlRoot("SiteServerRelationship", Namespace = "http://example.com/schemas/SiteServerRelationship")]
public class Relationship
{
public string type { get; set; }
}
public string Name { get; set; }
[XmlElement("SiteServerRelationship", Namespace="http://example.com/schemas/SiteServerRelationship")]
public Relationship Relate = new Relationship();
}
[XmlInclude(typeof(Relationship))]
public class LocalServer
{
[XmlRoot("LocalServerRelationship", Namespace = "http://example.com/schemas/LocalServerRelationship")]
public class Relationship
{
public string type { get; set; }
}
public string Name { get; set; }
[XmlElement("LocalServerRelationship", Namespace="http://example.com/schemas/LocalServerRelationship")]
public Relationship Relate = new Relationship();
}
[XmlRoot]
仅用于文档的根元素。您希望在其他类型上使用[XmlType]
此外,您不需要
[Serializable]
。XML序列化程序会忽略它。我在一个应用程序中使用的两个第三方Web服务存在此问题。奇怪的是,动态运行时生成很好(虽然只花了2分钟),但sgen.exe却感到不安
解决方案是使用svcutil.exe
svcutil.exe /t:xmlSerializer targetAssemblyOrExecutable /out:targetAssemblyOrExecutable.XmlSerializers.dll.cs
然后使用csc.exe编译它。XmlType修复了我的问题。谢谢也许随着问题的深入及其范围的缩小,在“公共类关系”之上使用XMLType(AnonymousType=true)可能会变得简单
svcutil.exe /t:xmlSerializer targetAssemblyOrExecutable /out:targetAssemblyOrExecutable.XmlSerializers.dll.cs