Search code examples
c#xmlxelement

How to add a node as a children to an existing node XElement?


Here is my code.

    XElement Response = new XElement("Response",
                                new XElement("RequestId", requestID),
                                new XElement("ResponseId", "E001"),
                                new XElement("Target", target));
    Response.Add(new XElement("templates"));

Now I want to add list of template within templates How do I do that? I use linq to find templates.

     var t = from e1 in wlnResponse.Elements()
                    where e1.Name.ToString() == "templates"
                    select e1;

Solution

  • I'd suggest storing templates XElement in a variable before adding it into your document:

    XElement templates = new XElement("templates");
    Response.Add(templates );
    

    And then use it to add templates:

    var t = from e1 in wlnResponse.Elements()
            where e1.Name.ToString() == "templates"
            select e1;
    
    templates.Add(t.ToArray());