views:

43

answers:

2

Assuming the following model

public class MyObject
{
    public string Name { get; set; }
    public ICollection<MyObjectItem> Items { get; set; }
}

public class MyObjectItem
{
    public string Name { get; set; }
    public int Total { get; set; }
}

I want to serialize and deserialize this object graph to a list of key/value pair of strings like :

MyObject.Name - "Name"

MyObject.Items.0.Name - "Name1"

MyObject.Items.0.Total - "10"

MyObject.Items.1.Name - "Name2"

MyObject.Items.1.Total - "20"

A: 

Object serialization is usually expensive for big xml structures. If it's possible, try to use XMlWriter or XmlTextWriter - usage example: http://dotnetperls.com/xmlwriter

UGEEN
A: 

Well, you could not use a built-in serializer for that, you would need a custom ToString() / Parse(), similar to this: (ToString() is kind of self explanatory)

MyObject obj = new MyObject();    

List<MyObjectItem> items = new List<MyObjectItem>();    

foreach (string line in text.Split) 
{ 
     // skip MyObject declaration int idx = line.IndexOf('.'); 
     string sub = line.Substring(idx); 
     if (sub.StartsWith("Name")) {
         obj.Name = sub.Substring("Name".Length + 3 /* (3 for the ' - ' part) */);
     }
     else
     {
          sub = sub.Substring("Items.".Length);
          int num = int.Parse(sub.Substring(0, sub.IndexOf('.'));
          sub = sub.Substring(sub.IndexOf('.' + 1);
          if (items.Count < num)
              items.Add(new MyObjectItem());
          if (sub.StartsWith("Name"))
          {
               items[num].Name = sub.SubString("Name".Length + 3);
          }
          else
          {
               items[num].Total = sub.SubString("Total".Length + 3);
          }
     }
}

obj.Items = items;

Hope this helps, as I do not have access to a C# IDE at this time...

Richard J. Ross III