views:

157

answers:

1

I have xml structure like this:

<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 is denotes Group's Id.

The Constructor of Group reads like:

public Group(string name, int ID, Group parent)

While De-serializing, how do I get parent using Id and pass into group?

+1  A: 

If you are using the inbuilt processing, then XmlSerializer only really wants to use the default constructor. You could do that 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 a Group parent and a parent-id. I suspect the best approach would be to either write the data in a more hierarchical fashion, or to stick with what you have, but use a simple DTO during deserialization. Then translate this data into what you actually want in the next stage. So, if you have:

List<GroupDTo> groups = ...

You might translate that 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.

Marc Gravell