简体   繁体   中英

Deserialise XML into class with attributes

I have one XML received by clients and I need to serialise it into class structure. Here is the XML structure.

<?xml version="1.0" encoding="utf-8"?>
<MainData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<listofChannels>
   <item type="DAY CHANNEL">
     <channelName>one</channelName>
     <channelPort>11</channelPort>
     <ServerDetail ipaddress="127.0.0.1" port="80"/>
    </item>
   <item type="NIGHT CHANNEL">
     <channelName>one</channelName>
     <channelPort>11</channelPort>
     <ServerDetail ipaddress="127.0.0.2" Port="80"/>
 </item>
</listofChannels>
</MainData>

Now I I'm trying to create a C# class to represent this and get List of channels. So I wrote this code , but i don't get this list, it is blank.

MainData mainData = new MainData();
var serializer = new XmlSerializer(typeof(MainData));
using (TextReader reader = new StreamReader(dataFilePath)) // dataFilePath is the FilePath
{
   mainData = (MainData)serializer.Deserialize(reader);
}

Here are my classes

public class MainData
{
    public List<Channel> listofChannels { get; set; }
}

public class Channel
{
    public string Type;
    [XmlAttribute("channelName")]
    public string Name;
    [XmlAttribute("channelPort")]
    public int Port;
    public ChannelDetail details;
}

public class ChannelDetail
{
    [XmlAttribute("ipaddress")]
    public string IPAddress { get; set; }

    [XmlAttribute("port")]
    public int Port { get; set; }
}

The element that is supposed to populate Channel class is named "item". Since they don't match you have to specify it manually (Same goes for ChannelDetail - ServerDetail).

Also some elements were mapped to attributes. I changed the class definitions as below and seems to be working fine now:

public class MainData
{
    public List<Channel> listofChannels { get; set; }
}

[XmlType("item")]
public class Channel
{
    [XmlAttribute("type")]
    public string Type;

    [XmlElement("channelName")]
    public string Name;

    [XmlElement("channelPort")]
    public int Port;

    [XmlElement("ServerDetail")]
    public ChannelDetail details;
}

public class ChannelDetail
{
    [XmlAttribute("ipaddress")]
    public string IPAddress { get; set; }

    [XmlAttribute("port")]
    public int Port { get; set; }
}

Also, the "port" attribute in ServerDetail is spelled differently in the sample in the question. Since XML is case-sensitive you have to make sure they all have the same casing and map that to the Port variable by using XmlAttribute["port"] or XmlAttribute["Port"].

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