简体   繁体   中英

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"):

<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. 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();
    }
}

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>

Notice DataType="string" on the IPAddress element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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