2015-11-05 154 views
0

我想序列化一些數據,我已經到這種XML格式,但不能實現相同。XMLArray具有不同的類型,但具有相同的元素名稱和我:類型屬性

期望的XML輸出低於:

<?xml version="1.0" encoding="utf-8"?> 
<Root xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
    <Datas> 
    <Data xmlns="" i:type="DataA"> 
     <Name>A1</Name> 
     <ADesc>Description for A</ADesc> 
    </Data> 
    <Data xmlns="" i:type="DataB"> 
     <Name>B1</Name> 
     <BDesc>Description for b</BDesc> 
    </Data> 
    </Datas> 
</Root> 

我係列化創建的類如下:

public class Data 
{ 
    [XmlElement("Name")] 
    public string Name { get; set; } 
} 

public class DataA : Data 
{ 
    [XmlElement("ADesc")] 
    public string ADesc { get; set; } 
} 

public class DataB : Data 
{ 
    [XmlElement("BDesc")] 
    public string BDesc { get; set; } 
} 

[XmlRoot("Root")] 
public class Root 
{ 
    [XmlArray("Datas")] 
    [XmlArrayItem(Type = typeof(Data))] 
    [XmlArrayItem(Type = typeof(DataA))] 
    [XmlArrayItem(Type = typeof(DataB))] 
    public List<Data> Datas { get; set; } 
} 

我使用以下方法用於序列:

internal static string Serialize(Root obj) 
{ 
    var ns = new XmlSerializerNamespaces(); 
    ns.Add("i", "http://www.w3.org/2001/XMLSchema-instance"); 

    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Root)); 

    using (StringWriter textWriter = new StringWriter()) 
    { 
     xmlSerializer.Serialize(textWriter, obj, ns); 
     return textWriter.ToString(); 
    } 
} 

但我得到的輸出是(這是不正確的):

<?xml version="1.0" encoding="utf-8"?> 
<Root xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
    <Datas> 
    <DataA> 
     <Name>A1</Name> 
     <ADesc>Description for A</ADesc> 
    </DataA> 
    <DataB> 
     <Name>B1</Name> 
     <BDesc>Description for b</BDesc> 
    </DataB> 
    </Datas> 
</Root> 

回答

0

爲了使用XmlSerializer生成{http://www.w3.org/2001/XMLSchema-instance}type屬性,您需要在您的對象圖,即對於所有子類的DataXXX附加[XmlInclude(typeof(XXX))]到聲明的類型某處Root類或Data類本身:

//[XmlInclude(typeof(DataA))] /* Could also go here if you prefer. */ 
//[XmlInclude(typeof(DataB))] /* Could also go here if you prefer. */ 
public class Data 
{ 
    [XmlElement("Name")] 
    public string Name { get; set; } 
} 

public class DataA : Data 
{ 
    [XmlElement("ADesc")] 
    public string ADesc { get; set; } 
} 

public class DataB : Data 
{ 
    [XmlElement("BDesc")] 
    public string BDesc { get; set; } 
} 

[XmlRoot("Root")] 
[XmlInclude(typeof(DataA))] 
[XmlInclude(typeof(DataB))] 
public class Root 
{ 
    [XmlArray("Datas")] 
    public List<Data> Datas { get; set; } 
} 

欲瞭解更多信息,請參閱聲明序列化類型Troubleshooting Common Problems with the XmlSerializerXsi:type Attribute Binding Support

相關問題