XML序列化错误:2种类型都使用XML类型名称“关系”,来自命名空间”
我在通过XML序列化时遇到问题,因为2个clases使用一个名为Relationship的类(尽管是不同的类!)。 我尝试使用XML属性用另一个名称装饰其中一个类,但它仍然给我以下错误:
{“Types’SiteServer.Relationship’和’LocalServer.Relationship’都使用XML类型名称’Relationship’,来自命名空间”。使用XML属性为类型指定唯一的XML名称和/或命名空间。”}
这是我的2个class,有谁知道为什么? 我使用错误的属性? 它似乎忽略了它:-)
public class SiteServer { [XmlRoot("SiteServerRelationShip")] public class Relationship { public string type { get; set; } } public string Name { get; set; } public Relationship Relate = new Relationship(); } public class LocalServer { public class Relationship { public string type { get; set; } } public string Name { get; set; } public Relationship Relate = new Relationship(); }
用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(); }
这将为两个RelationShip类生成两个不同的FQDN:
{http://example.com/schemas/LocalServer}LocalServerRelationShip {http://example.com/schemas/SiteServer}SiteServerRelationShip
[XmlRoot]
仅用于文档的根元素。 您想在其他类型上使用[XmlType]
。
此外,您不需要[Serializable]
。 XML Serializer忽略它。
您还必须装饰字段,例如:
[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(); }
我在一个应用程序中使用的两个第三方Web服务遇到了这个问题。 奇怪的是,动态运行时生成很好(虽然花了2分钟),但是sgen.exe很不高兴。
解决方案是使用svcutil.exe …
svcutil.exe /t:xmlSerializer targetAssemblyOrExecutable /out:targetAssemblyOrExecutable.XmlSerializers.dll.cs
然后使用csc.exe编译它。