如何在xml序列化中显示数据类型? [英] How to show data types in xml serialization?

查看:35
本文介绍了如何在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="string"):

and I need the xml to show the data types in some of the elements (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>

有什么建议吗?

推荐答案

您可以在充当子元素的类中创建一个属性来充当数据类型属性,并使用给定对象上的反射执行以下操作.MethodBase 有一个名为 ReturnType 的属性,它将为您提供返回类型.

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. MethodBase has a property called ReturnType which will give you the returning type.

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

这将产生以下 xml 行

This would produce the following line of 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 元素上的 DataType="string".

Notice DataType="string" on the IPAddress element.

这篇关于如何在xml序列化中显示数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆