简体   繁体   English

如何在xml序列化中显示数据类型?

[英]How to show data types in xml serialization?

I have this Class: 我有这个课程:

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; }
    }

and I need the xml to show the data types in some of the elements (dt:dt="string"): 并且我需要xml以显示某些元素中的数据类型(dt:dt =“ string”):

<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>

any suggestions? 有什么建议么?

You could create a property inside your classes that are acting as child elements to act as the data type attribute and do the following using reflection on the give object. 您可以在充当子元素的类中创建一个属性,以充当数据类型属性,并使用对Give对象的反射来执行以下操作。 MethodBase has a property called ReturnType which will give you the returning type. MethodBase具有一个称为ReturnType的属性,该属性将为您提供返回类型。

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

This would produce the following line of xml 这将产生以下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>

Notice DataType="string" on the IPAddress element. 注意IPAddress元素上的DataType =“ string”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM