how to add XElement in specific location in XML Document

Search element you want to add and use Add method as shown below

xDoc.Element("content")
    .Elements("item")
    .Where(item => item.Attribute("id").Value == "2").FirstOrDefault()
    .AddAfterSelf(new XElement("item", "C", new XAttribute("id", "3")));

or

<Microsoft>
<DOTNet>

</DOTNet>
</Microsoft>
private void addToXml()
{
    XDocument xmlDoc = XDocument.Load("yourfile.xml");

    xmlDoc.Element("Microsoft").Add(new XElement("DOTNet", new XElement("Name", "Nisar"),
        new XElement("Forum", "dotnetobject"), new XElement("Position", "Member")));

    xmlDoc.Save("yourfile.xml");
    readXml();
}
<Microsoft>
<DOTNet>
  <Name>Nisar</Name>
  <Forum>dotnetobject</Forum>
  <Position>Member</Position>
</DOTNet>
</Microsoft>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)