开发者

XML Deserialization of complex object

开发者 https://www.devze.com 2022-12-26 05:56 出处:网络
I have xml structure like this: <Group id=\"2\" name=\"Third\" parentid=\"0\" /> <Group id=\"6\" name=\"Five\" parentid=\"4\" />

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消