2013-02-14 37 views
0

我有這個類:如何在xml序列化中顯示數據類型?

public class Computer 
    { 
     [XmlAttribute("StorageType")] 
     public int StorageType { get; set; } 

     [XmlAttribute("StorageName")] 
     public string StorageName { get; set; } 

     public string IPAddress { get; set; } 
     public string Name { get; set; } 
    } 

,我需要的XML來顯示數據類型中的一些元素(DT:DT = 「字符串」):

<fpc4:Computer StorageName="{D37291CA-D1A7-4F34-87E4-8D84F1397BEA}" StorageType="1"> 
     <fpc4:IPAddress dt:dt="string">127.0.0.1</fpc4:IPAddress> 
     <fpc4:Name dt:dt="string">Computer1</fpc4:Name> 
    </fpc4:Computer> 

有什麼建議?

回答

1

您可以在您的類中創建一個屬性,作爲子元素充當數據類型屬性,並在給定對象上使用反射執行以下操作。 MethodBase有一個名爲ReturnType的屬性,它會給你返回的類型。

[XmlAttribute("DataType")] 
public string DataType 
{ 
    get 
    { 
     return typeof(IPAddress).GetProperty("DataType").GetGetMethod().ReturnType.ToString(); 
    } 
} 

這將產生下面的行XML的

<fpc4:Computer StorageName="{D37291CA-D1A7-4F34-87E4-8D84F1397BEA}" StorageType="1"> 
     <fpc4:IPAddress DataType="string">127.0.0.1</fpc4:IPAddress> 
     <fpc4:Name dt:dt="string">Computer1</fpc4:Name> 
</fpc4:Computer> 

通知數據類型的的IPAddress元件上= 「字符串」。