按类型属性的XML序列化

时间:2016-08-12 09:55:06

标签: c# xml serialization soap

我有这样的情况:

[Serializable]
[XmlType]
public class MyMessage
{
    [XmlElement]
    public object data;
}
[Serializable]
[XmlType(Namespace = "http://comp.com/types")]
public class SomeClass
{
    [XmlElement]
    public string SomeString { get; set; }

    [XmlElement]
    public int SomeInt { get; set; }
}
[Serializable]
[XmlType(Namespace = "http://comp.com/types")]
public class OtherClass
{
    [XmlElement]
    public string OtherString { get; set; }

    [XmlElement]
    public int OtherInt { get; set; }
}

我需要像这样得到xml:

<data xsi:type="ns1:SomeClass" xmlns:ns1="http://comp.com/types">
    <SomeString>someValue</SomeString>
    <SomeInt>10</SomeInt>
</data>

<data xsi:type="ns1:OtherClass" xmlns:ns1="http://comp.com/types">
    <OtherString>someValue</OtherString>
    <OtherInt>10</OtherInt>
</data>

我尝试添加到data字段属性:

[XmlElement("data", typeof(SomeClass), Namespace = "http://comp.com/types")]

它几乎可以工作,但缺少xml属性type。如果我为第二课XmlElement添加OtherClass,我会收到错误:

  

来自命名空间“http://comp.com/types”的顶级XML元素“data”引用了不同类型ObjectModel.SomeClass和ObjectModel.OtherClass。使用XML属性为元素指定另一个XML名称或命名空间。   有可能解决这个问题吗?此代码用于SOAP服务。

1 个答案:

答案 0 :(得分:0)

试试这个

    [Serializable]
    [XmlType]
    public class MyMessage
    {
        [XmlElement]
        public List<BaseClass> data;
    }
    [XmlInclude(typeof(SomeClass))]
    [XmlInclude(typeof(OtherClass))]

    [Serializable]
    public class BaseClass
    {
    }
    [Serializable]
    [XmlType(Namespace = "http://comp.com/types")]
    public class SomeClass : BaseClass
    {
        [XmlElement]
        public string SomeString { get; set; }

        [XmlElement]
        public int SomeInt { get; set; }
    }
    [Serializable]
    [XmlType(Namespace = "http://comp.com/types")]
    public class OtherClass : BaseClass
    {
        [XmlElement]
        public string OtherString { get; set; }

        [XmlElement]
        public int OtherInt { get; set; }
    }