2015-11-06 72 views
0

我以某種方式無法實現此序列化。我有這些類序列化派生類的根作爲基類名的類型

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

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

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

當我序列要麼DataA的或數據B我應該得到個XML的結構如下:

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="DataA"> 
     <Name>A1</Name> 
     <ADesc>Description for A</ADesc> 
</Data> 

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="DataB"> 
     <Name>B1</Name> 
     <BDesc>Description for b</BDesc> 
</Data> 

我所得到的是以下(不含我:TYPE =」 ...「和xmlns =」「)

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
     <Name>A1</Name> 
     <ADesc>Description for A</ADesc> 
</Data> 

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
     <Name>B1</Name> 
     <BDesc>Description for b</BDesc> 
</Data> 

我不知道我在這裏錯過了什麼。任何的意見都將會有幫助。

  • 吉里賈·
+0

HTTP ://stackoverflow.com/questions/2339782/xml-serialization-and-namespace-prefixes也許這將有助於 – Doro

回答

1

您應該包括派生類型的基類的XML序列化。

然後你就可以創建一個串行爲鹽基型的,而當你係列化任何派生類型,這將增加該類型的屬性:(你甚至可以從派生類現在刪除[ROOT] sttribute)

[XmlInclude(typeof(DataA))] 
[XmlInclude(typeof(DataB))] 
[XmlRoot("Data", Namespace = Data.XmlDefaultNameSpace)] 
public class Data 
{ 
    public const string XmlDefaultNameSpace = "http://www.stackoverflow.com/xsd/Data"; 

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

序列化:

DataA a = new DataA() { ADesc = "ADesc", Name = "A" }; 
DataB b = new DataB() { BDesc = "BDesc", Name = "B" }; 
new XmlSerializer(typeof(Data)).Serialize(Console.OpenStandardOutput(), a); 
new XmlSerializer(typeof(Data)).Serialize(Console.OpenStandardOutput(), b); 

這裏是輸出爲DataA的類的序列

<?xml version="1.0"?> 
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="DataA" xmlns="http://www.stackoverflow.com/xsd/Data"> 
    <Name>A</Name> 
    <ADesc xmlns="">ADesc</ADesc> 
+0

謝謝,我得到了我:類型。但是,我如何獲得xmlns =「」..這不是在結果XML中。 – Shankar

+0

編輯我的答案。你想要命名空間爲空嗎?在這種情況下,它不打印nameace –

+0

是的,我需要空的。但我現在測試值和空值,並且在任何情況下都不打印 – Shankar