2016-08-12 12 views
0

私はこのような状況を持っている:私はdataフィールドに追加してみてくださいXMLシリアル化

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

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

と:

[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を取得する必要があります属性:

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

ほとんどの作業ですが、xml属性typeがありません。私は第二のクラスOtherClassためXmlElementを追加する場合と、私はエラーを取得:

The top XML element 'data' from namespace ' http://comp.com/types ' references distinct types ObjectModel.SomeClass and ObjectModel.OtherClass. Use XML attributes to specify another XML name or namespace for the element or types. Is it possible to solve this problem? This code use in SOAP service.

+0

標準のXMLが唯一の1つのルートタグを持ってしてみてください。 2つのデータタグをルートに配置しようとしています。 – jdweng

+0

もちろん、私はルートに2つのデータタグを入れようとはしません。私は 'SomeClass'または' OtherClass'を両方に入れたくありません。 –

+0

あなたのモデルは間違っています、 'data'はあなたのルートです.'SomeClass' *は' data'です.MyMessageはありません。残念ながら、あなたは[これと似たような](https://dotnetfiddle.net/TsvMjR)に近づくことができますが、シリアライザは別の名前空間にサブクラスを持つことはできません。 –

答えて

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