Question : Serialize/Deserialize Enums to xml in C#

Hi,

I am new to XML and am trying to figure out how to deserialize enums in my project.  I have a class called Town.  I have a static class with enumerators describing the town - has a Hospital, Professional sports team, etc.)  called TownFeature.

I can serialize it fine (I think) by examining the value of the enum an calling ToString() on it, but I am having trouble conceptualizing how to essentially cast the xml element to my enum.  

Can someone help me out with this (with sample code if possible)?

Thanks,

Robert
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
public class Town
{ 

    public List Has { get; set; } 
    public List Is { get; set; }    
     
    public Town()
    { 
        Has = new List();
        Is = new List();
    } 
    public string Serialize()
    {
        XElement _has = null;
        XElement _is = null; 
        XName name = "Town";
        XElement element = new XElement(name);  
          
        XName hasName = "Has";
        XName isName = "Is"; 
        //return an XML-formatted list instead of the List 
        //because we cannot serialize enums.
        foreach (TownFeature.Has item in Has)
        {
            _has = new XElement(hasName);
            _has.Value = item.ToString();
            element.Add(_has);
        } 
        foreach (TownFeature.Is item in Is)
        {
            _is = new XElement(isName);
            _is.Value = item.ToString();
            element.Add(_is);
        }
        return element.ToString();
    } 
    public Deserialize(XElement xml)
	{
        var town = from t in xml.Elements("Town")
                   select t; 
        foreach (XElement x in town)
        {
            if (x.Name == "Has")
            {
                Has.Add( !!! ACK !!! this is where I'm stuck);
            }
        }
	}
} 

public static class TownFeature
{
    public enum Has
    {
        Hospital,
        ProfessionalSportsTeam
    } 
}

Answer : Serialize/Deserialize Enums to xml in C#

>>My guess is no, but can you confirm?
yes, i checked it and it workd fine.

>>As for Q1 above...
its really up to you, its not something that affect the logic of your code.
INMO, as a programatic method, i always use private fields and set/get properties unless there's a specialcondition which requires special design.
Random Solutions  
 
programming4us programming4us