[英]Xml Deserialize Class with property object
我想知道如何從XML反序列化到包含對象的類,該對象可以是ARS或BRS中的任何一個
ARS和BRS是從XSD文件生成的,因為ARS和BRS都包含屬性C,所以在使用新的序列化程序時它將失敗
錯誤:System.InvalidOperationException:'反映類型'TestXml.Response'的錯誤。
InvalidOperationException:類型'BC'和'AC'都使用名稱空間''中的XML類型名稱'C'。 使用XML屬性為類型指定唯一的XML名稱和/或名稱空間。
我試圖將名稱空間添加到ARS.C和BRS.C,但是由於響應不包含名稱空間,因此它返回null
任何建議都會有所幫助,謝謝。
父類“響應”
namespace TestXml
{
[XmlRoot(Namespace="")]
public class Response
{
[XmlElement(ElementName = "ARS", Type = typeof(ARS))]
[XmlElement(ElementName = "BRS", Type = typeof(BRS))]
public object Object;
}
}
ARS類
namespace A
{
public class ARS
{
public int a;
public C c;
}
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class C
{
public string d;
}
}
BRS類
namespace B
{
public class BRS
{
public int b;
public C c;
}
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class C
{
public int e;
}
}
通過XmlSerializer反序列化
string ooo = @"<Response xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><ARS><a>1</a><c><d>ca</d></c></ARS></Response>";
XDocument xDoc = XDocument.Parse(ooo);
XmlSerializer ser = new XmlSerializer(typeof(Response));
using (var reader = xDoc.CreateReader(System.Xml.Linq.ReaderOptions.OmitDuplicateNamespaces))
{
Response deserializedObject = (Response)ser.Deserialize(reader);
}
我最終使用xml linq首先提取響應字符串的子部分,然后逐個反序列化,這樣就不再存在沖突
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.