2016-08-12 216 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; } 
    }