简体   繁体   English

Xml反序列化带有属性对象的类

[英]Xml Deserialize Class with property object

I would like to know how to deserialize from XML to a class that contains an object which may be any of classes ARS or BRS 我想知道如何从XML反序列化到包含对象的类,该对象可以是ARS或BRS中的任何一个

ARS and BRS are generated from XSD files As ARS and BRS both contains property C, then it fails when new Serializer ARS和BRS是从XSD文件生成的,因为ARS和BRS都包含属性C,所以在使用新的序列化程序时它将失败

Error: System.InvalidOperationException: 'There was an error reflecting type 'TestXml.Response'.' 错误:System.InvalidOperationException:'反映类型'TestXml.Response'的错误。

InvalidOperationException: Types 'BC' and 'AC' both use the XML type name, 'C', from namespace ''. InvalidOperationException:类型'BC'和'AC'都使用名称空间''中的XML类型名称'C'。 Use XML attributes to specify a unique XML name and/or namespace for the type. 使用XML属性为类型指定唯一的XML名称和/或名称空间。

I tried to add namespace to ARS.C and BRS.C but since the response does not contain the namespace, it returns null 我试图将名称空间添加到ARS.C和BRS.C,但是由于响应不包含名称空间,因此它返回null

Any suggestion would help, thanks. 任何建议都会有所帮助,谢谢。

Parent class "Response" 父类“响应”

namespace TestXml
{
    [XmlRoot(Namespace="")]
    public class Response
    {
        [XmlElement(ElementName = "ARS", Type = typeof(ARS))]
        [XmlElement(ElementName = "BRS", Type = typeof(BRS))]
        public object Object;
    }
}

Class ARS 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;
    }
}

Class BRS 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;
    }
}

Deserialize by XmlSerializer 通过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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM