Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过LINQ向XElement添加子元素_C#_Xml_Linq - Fatal编程技术网

C# 通过LINQ向XElement添加子元素

C# 通过LINQ向XElement添加子元素,c#,xml,linq,C#,Xml,Linq,我有一个类的集合,看起来像: public class Group { public string Name { get; set; } } private ObservableCollection<Group> _groups; <Ou> <Group>AAA</Group> <Group>BBB</Group> <Group>CCC</Group> <

我有一个类的集合,看起来像:

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

private ObservableCollection<Group> _groups;
<Ou>
    <Group>AAA</Group>
    <Group>BBB</Group>
    <Group>CCC</Group>
    <Group>DDD</Group>
</Ou>
但是不知道如何继续编码。

像这样:

var element =
    new XElement(
        "Ou",
        new XElement("Group", "AAA"),
        new XElement("Group", "BBB"),
        new XElement("Group", "CCC"),
        new XElement("Group", "DDD"));
或者从您的数据结构:

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

var element =
    new XElement(
        "Ou",
        new XElement("Group", "AAA"),
        new XElement("Group", "BBB"),
        new XElement("Group", "CCC"),
        new XElement("Group", "DDD"));
或者从您的数据结构:

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

您可以尝试以下代码:

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"));
...

您可以尝试以下代码:

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"));
...