Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add XElement in specific location in XML Document

I want to create an XML document like this:

Xml Doc

I want to create it from scratch using code and LINQ-to-XML. In the form Load Event I've written this code:

private void Form9_Load(object sender, EventArgs e) {     doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));     XElement myroot = new XElement("Employees");     doc.Add(myroot); } 

How I can add new person to Employees, and if I want to insert person in specific location what can I do?

How I can delete or update a specific person ?

like image 955
Arian Avatar asked Apr 20 '11 05:04

Arian


People also ask

What is XElement C#?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


1 Answers

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> 
like image 194
Pranay Rana Avatar answered Sep 28 '22 18:09

Pranay Rana