Home > Code > LINQ > Insert an xml element after specific node using LINQ to XML AddAfterSelf() method.

Insert an xml element after specific node using LINQ to XML AddAfterSelf() method.

by Thamil   on Oct 20, 2011   Category: LINQ   |  Views: 8112    |  Points: 25   |  Gold 


In this code snippet, i will describe how to add new data in the existing XML file after specific element see the below sample xml and code

<company>
<department>
<name>Finance</name>
<name>Admin</name>
<name>Help desk</name>
<name>IT</name>
</department>
<customer>
<name>John</name>
</customer>
<locations>
<name>UK</name>
<name>US</name>
</locations>
</company>


here i want to add the name in the customer section see the below sample code. Using AddAfterSelf() method, We can add the content after specific node.

XDocument compDoc = new XDocument();
compDoc = XDocument.Load(@"xml path...");
compDoc.Element("company").Element("customer").Element("name").AddAfterSelf(new XElement("name", "Prakal"));
string updatedXML = compDoc.ToString();


The updatedXML string will have the below xml after adding the name in the after specific node.

<company>
<department>
<name>Finance</name>
<name>Admin</name>
<name>Help desk</name>
<name>IT</name>
</department>
<customer>
<name>John</name>
<name>Prakal</name>
</customer>
<locations>
<name>UK</name>
<name>US</name>
</locations>
</company>




Post Code  |  Code Snippet Home

User Responses


No response found, be the first to review this code snippet.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts