softshipper
softshipper

Reputation: 34061

Add children to XElement via LINQ

I have a Collection of a class that looks like:

public class Group
{
   public string Name { get; set; }
}

private ObservableCollection<Group> _groups;

now I want to create a xml structure from groups that looks like:

<Ou>
    <Group>AAA</Group>
    <Group>BBB</Group>
    <Group>CCC</Group>
    <Group>DDD</Group>
</Ou>

I have try following:

new XElement("Ou", //How continue here?)

but do not know how to continue coding.

Upvotes: 0

Views: 43

Answers (3)

Yuri Dorokhov
Yuri Dorokhov

Reputation: 726

You can try following code:

var element = new XElement("Ou");
element.Add(new XElement("Group", "AAA"));
element.Add(new XElement("Group", "BBB"));
element.Add(new XElement("Group", "CCC"));
element.Add(new XElement("Group", "DDD"));
...

Upvotes: 0

Glorfindel
Glorfindel

Reputation: 22631

new XElement("Ou", _groups.Select(g => new XElement("Group", g.Name)));

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117029

Like this:

var element =
    new XElement(
        "Ou",
        new XElement("Group", "AAA"),
        new XElement("Group", "BBB"),
        new XElement("Group", "CCC"),
        new XElement("Group", "DDD"));

Or from your data structure:

var element =
    new XElement("Ou",
        from g in _groups
        select new XElement("Group", g.Name));

Upvotes: 3

Related Questions