Cybercop
Cybercop

Reputation: 8678

LINQ: add child element inside an element

I know there have been many related questions like this before for example here

But I am not being able to solve one simple problem.

Here is an example

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

This yeilds following result

enter image description here

All good till here. Now I want to add new child element inside subroot.

This is what I have tried

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

This however throws exception saying Object reference not set to instance of an object.

Another try was

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

This says cannot find matching element.

Could someone explain what is happening and why I am getting these errors. And how to add child element. In my case inside subroot element

Upvotes: 0

Views: 699

Answers (1)

Xiaoy312
Xiaoy312

Reputation: 14477

subroot is not a direct child of the document. You should use Descendents instead:

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

Upvotes: 3

Related Questions