0

looking for best practice in converting a parent-child relationship using Linq to XML

In this case i have a Domain class which contains a Group[]

What I want to do is iterate over the Groups[] in d (domains) and create the XElements in one hit.

        XElement _customers = new XElement("Domains",
                                from c in d
                                orderby c.id //descending  
                                select new XElement("Domain",
                      // something like-->  new XElement("Groups", c.id),
                      // loop through d.Group and add new XElement...
                                    new XElement("id", c.id),
                                    new XAttribute("name", c.name),
                                    new XElement("ismanaged", c.IsManaged.ToString()
                                    )));

Thanks in advance

1 Answer 1

1

You can use nested queries to do this.

Assuming your classes look like this (simplifying a little bit):

public class Domain
{
    public string Name;
    public List<Group> Groups;
}

public class Group
{
    public string GroupId;
}

You can create LINQ to XML representation in one go like this:

XElement domains = new XElement("Domains",
    from domain in domains
    select new XElement("Domain",
        new XAttribute("name", domain.Name),
        from group in domain.Groups
        select new XElement("Group",
            new XAttribute("id", group.GroupId))
    ));

The "trick" is that if you pass an IEnumerable as one of the parameters to the XElement constructor, the constructor will enumerate over it and add each item separately.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.