Insert an XML node in front of a specific node using C #

This is my xml file

<employee> <name ref="a1" type="xxx"></name> <name ref="a2" type="yyy"></name> <name ref="a3" type="zzz"></name> </employee> 

Using C #, I need to insert this node

 <name ref="b2" type="aaa"></name> 

between nodes "a2" and "a3". Any pointer how to sort this?

+7
c # xml
source share
1 answer

use the insertAfter method:

 XmlDocument xDoc = new XmlDocument(); xDoc.Load(yourFile); XmlNode xElt = xDoc.SelectSingleNode("//name[@ref=\"a2\"]"); XmlElement xNewChild = xDoc.CreateElement("name"); xNewChild.SetAttribute("ref", "b2"); xNewChild.SetAttribute("type", "aaa"); xDoc.DocumentElement.InsertAfter(xNewChild, xElt); 
+9
source share

All Articles