//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.查询添加Xml节点
//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.删除Xml节点
child3.Remove();