2013-02-14 46 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元件上= “字符串”。