假设以下模型
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; }
}
我想将此对象图序列化和反序列化为键/值对字符串列表,如:
MyObject.Name - “名称”
MyObject.Items.0.Name - “Name1”
MyObject.Items.0.Total - “10”
MyObject.Items.1.Name - “Name2”
MyObject.Items.1.Total - “20”
答案 0 :(得分:0)
对于大型xml结构,对象序列化通常很昂贵。如果可能,请尝试使用XMlWriter
或XmlTextWriter
- 使用示例:http://dotnetperls.com/xmlwriter
答案 1 :(得分:0)
好吧,你不能使用内置的序列化程序,你需要一个自定义的ToString()/ Parse(),类似于:( ToString()是一种自我解释)
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;
希望这会有所帮助,因为我此时无法访问C#IDE ...