XML deserialization of a complex object
I have an xml structure:
<Group id="2" name="Third" parentid="0" />
<Group id="6" name="Five" parentid="4" />
<Group id="3" name="Four" parentid="2" />
<Group id="4" name="Six" parentid="1" />
parent denotes the group id.
The group constructor reads like this:
public Group(string name, int ID, Group parent)
While De-serializing, how do I get the parent id and pass it to the group?
source to share
If you are using inline processing then XmlSerializer
really wants to use the default constructor. You can do this via:
public class Group {
public Group() {}
[XmlAttribute("id")]
public int Id {get;set;}
[XmlAttribute("name")]
public string Name {get;set;}
[XmlAttribute("parentid")]
public int ParentId {get;set;}
}
but note that there is a big difference between parent Group
and parent-id. I suspect that the best approach would be to either write the data in a more hierarchical way, or stick with what you have and use a simple DTO during deserialization. Then translate that data into what you really want in the next step. So, if you have:
List<GroupDTo> groups = ...
You can translate this as:
var actualGroups = from group in groups
select new Group(group.Id, group.Name,
groups.FirstOrDefault(x => x.Id == group.ParentId));
this should do what you need.
source to share