LINQ:在元素内添加子元素

LINQ: add child element inside an element

我知道以前有很多这样的相关问题 例如 here

但我无法解决一个简单的问题。

这是一个例子

        int id = 1;
        var doc = new XDocument(new XDeclaration("1.0","utf-8","yes"));
        doc.Add(new XElement("root", new XAttribute("Version", "1.1.0")));
        doc.Root.Add(new XElement("subroot", new XAttribute("ID", id)));
        Console.WriteLine(doc);

这会产生以下结果

到这里为止一切都很好。 现在我想在 subroot 中添加新的子元素。

这是我试过的

        doc.Element("subroot").Add(new XElement("InsideSubroot"), new XAttribute("name","xyz"));

然而,这会抛出异常,指出对象引用未设置为对象的实例。

另一个尝试是

    doc.Elements("subroot").Single(x=> (int) x.Attribute("ID") == id).Add(new XElement("InsideSubroot"), new XAttribute("name","xyz"));

这表示找不到匹配的元素。

有人可以解释发生了什么以及为什么我会收到这些错误。 以及如何添加子元素。在我的例子中,子根元素

subroot 不是文档的直接子项。您应该改用 Descendents

doc
    .Descendants("subroot")
    .Single(x => (int)x.Attribute("ID") == id)
    .Add(new XElement("InsideSubroot"), new XAttribute("name","xyz"));