1. Use Linq to create an XML
// Create dummy XML to work
Var root = new XElement ("parent ",
From I in new int [] {1, 2, 3, 4, 5, 6}
Select new XElement ("child ",
New XAttribute ("number", I )));
This will create XML like,
<? Xmlversion = "1.0" encoding = "UTF-8"?>
<Parent>
<Childnumber = "1"/>
<Childnumber = "2"/>
<Childnumber = "3"/>
<Childnumber = "4"/>
<Childnumber = "5"/>
<Childnumber = "6"/>
</Parent>
2. query and add an Xml Node
// Get the element (child3)
XElement child3 = root. Descendants ("child"). First (
El => (int) el. Attribute ("number") = 3 );
// Add element before the child3
Child3.AddBeforeSelf (new XElement ("child25 "));
// Add sub-element to the child3
Child3.Add (new XElement ("grandchild "));
// Add element after the child3
Child3.AddAfterSelf (new XElement ("child35 "));
// Add attribute to the child3
Child3.Add (new XAttribute ("attr", "something "));
// Change the existing attribute
Child3.SetAttributeValue ("number", 100 );
After all these activities you will get the following output,
<? Xmlversion = "1.0" encoding = "UTF-8"?>
<Parent>
<Childnumber = "1"/>
<Childnumber = "2"/>
<Child25/>
<Childnumber = "100" attr = "something">
<Grandchild/>
</Child>
<Child35/>
<Childnumber = "4"/>
<Childnumber = "5"/>
<Childnumber = "6"/>
</Parent>
3. delete an Xml Node
Child3.Remove ();