views:

22

answers:

1

Hi all,

I am looking forward to serialize a Dictionary in order to save some of it's information, more precisely it's Key and one of it's Value, into Silverlight Isolated storage. I have read many question talking about the same subject on these boards, but none were explaining what I was trying to do, or at least not in a way I could understand. I also don't know with what I could serialize it: XmlSerializer, JSON, etc... I am trying to perform this serialization in order to 'save' some of the user settings, I don't intend to send them to a Web service or anything, it's only use will be inside the application.

Here is the structure of my Dictionary:

static Dictionary<string, User> Mydictionary

And here is the 'User' class:

public class User
{
    public User()
    {

    }

    public string name;
    public string age;
    public string groups;
}

I would like to save the Key and the 'groups' Value of my object and serialize only those two informations. I was asking myself if it was even possible?

Thank you, Ephismen.

+1  A: 

Serializin/deserializing XML with Linq is very easy, I strongly recommend you take a look at it if you don't know it yet.

Serialization will look like this:

// add reference to System.Xml.Linq

var xml = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("users",
    from pair in dic
    select new XElement("user",
        new XAttribute("userId", pair.Key),
        new XAttribute("Groups", pair.Value.groups))));

// xml.Save(...) to save in the IsolatedStorage

Deserialization:

XDocument loaded = XDocument.Load(...your stream...);

var results = from c in loaded.Descendants("users")
        select new {
            userIdAttribute = (string)c.Attribute("userId"),
            groupsAttribute = (string)c.Element("Groups")
        };

foreach (var user in results)
{
    dic.Add(user.userIdAttribute,
        new User()
        {
            name = user.userIdAttribute,
            groups = user.groupsAttribute
        });
}

You can find some good documentation here and some examples here.

Francesco De Vittori
Thank you very much,the example and links you provided are very clear and useful. I got one more question, I know how to save in Isolated storage, but is it possible to get the file and cast it into an xml document? or I need to parse like some sort of string?
Ephismen
I added a deserialization example. XDocument.Load takes either a file name or a stream. If you are in the browser you cannot access the filesystem, so you will have to read/write from the IsolatedStorage and get a stream from the file in there. (does this answer your question?)
Francesco De Vittori
Perfectly, thank you very much you saved my day :)
Ephismen