2016-08-12 147 views
0

我有這樣的情況:XML序列化

[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,我得到錯誤:

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只有一個根標籤。您正試圖在根上放置兩個數據標籤。 – jdweng

+0

當然,但我不想將兩個數據標記放在根上。我想把'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; } 
    }