Here is a solution without using LINQ to XML. It's implemented as an extension method for the XmlNode
class:
public static void InsertAt(this XmlNode node, XmlNode insertingNode, int index = 0)
{
if(insertingNode == null)
return;
if (index < 0)
index = 0;
var childNodes = node.ChildNodes;
var childrenCount = childNodes.Count;
if (index >= childrenCount)
{
node.AppendChild(insertingNode);
return;
}
var followingNode = childNodes[index];
node.InsertBefore(insertingNode, followingNode);
}
Now, you can insert a node at the desired position as simple as:
parentXmlNode.InsertAt(childXmlNode, 7);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…