I suggest to use helper methods. First one is to create dictionary of values from your strange xml data format (it uses key
element value as dictionary entry key, and next node as dictionary entry value):
static Dictionary<string, XElement> GetValues(XElement dict)
{
return dict.Elements("key")
.ToDictionary(k => (string)k, k => (XElement)k.NextNode);
}
Second one is parsing MyObject
:
static MyObject ParseMyObject(XElement dict)
{
var values = GetValues(dict);
return new MyObject
{
MainTitle = (string)values["Title"],
ListOfSubTitles = values["ID"].Elements().Select(s => (string)s).ToList()
};
}
All parsing will look like:
XDocument xdoc = XDocument.Load(path_to_xml);
var result =
xdoc.Root.Elements("dict")
.Select(GetValues)
.ToDictionary(v => (string)v["MainTitle"],
v => v["SubTopics"]
.Elements("dict").Select(ParseMyObject).ToList());
Result of parsing:
{
"Data": [
{
MainTitle: "Miscellaneous",
ListOfSubTitles: [ "CD1", "CD2", "CD3", "CD4" ]
},
{
MainTitle: "Miscellaneous One",
ListOfSubTitles: [ "DDC1", "DDC2", "DDC3", "DDC4", "DDC5" ]
}
],
"Data Two": [
{
MainTitle: "Goblins",
ListOfSubTitles: [ "SSD1", "SS2", "SS3", "SS4" ]
},
{
MainTitle: "Tracks",
ListOfSubTitles: [ "ADC1", "ADC2", "ADC3", "ADC4", "DDC5" ]
}
]
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…