Add XElement to another XElement in specific location

c#, c#-4.0, linq-to-xml, xelement, xml

Solution

First you need to load the xml string, second you get the position where you want to insert the xml, then insert the new xml. Here is an example how to do it.

var reader = new StringReader(@"<Employees>
    <Person>
        <ID>1000</ID>
        <Name>Nima</Name>
        <LName>Agha</LName>
    </Person>
    <Person>
        <ID>1002</ID>
        <Name>Ligha</Name>
        <LName>Ligha</LName>
    </Person>
    <Person>
        <ID>1003</ID>
        <Name>Jigha</Name>
        <LName>Jigha</LName>
    </Person>
</Employees>");
var xdoc = XDocument.Load(reader);
xdoc.Element("Employees").
   Elements("Person").
   First().
   AddAfterSelf(new XElement("Person", 
       new XElement("ID", 1001),
       new XElement("Name", "Aba"),
       new XElement("LName", "Aba")));

var sb = new StringBuilder();
var writer = new StringWriter(sb);
xdoc.Save(writer);
Console.WriteLine(sb);

UPDATE

If you want to insert by index, just get the element first. For example you want to insert as second position, then you need to get the first index (index = 0).

var xdoc = XDocument.Load(reader);
xdoc.Element("Employees").
    Elements("Person").
    ElementAt(0).
    AddAfterSelf(new XElement("Person", 
        new XElement("ID", 1001),
        new XElement("Name", "Aba"),
        new XElement("LName", "Aba")));

PS: For simplicity purpose I didn't add nullity check.

Problem

Please consider this `XML`: ``` <Employees> <Person> <ID>1000</ID> <Name>Nima</Name> <LName>Agha</LName> </Person> <Person> <ID>1002</ID> <Name>Ligha</Name> <LName>Ligha</LName> </Person> <Person> <ID>1003</ID> <Name>Jigha</Name> <LName>Jigha</LName> </Person> </Employees> ``` That is content of a `XElement` variable.Now I have another `XElement` variable with this content: ``` <Person> <ID>1001</ID> <Name>Aba</Name> <LName>Aba</LName> </Person> ``` I want to add this `XEelemnt` variable to first `XElement` in a specific position (for example as second `Person` tag). How I can do this? thanks

Original source