Inserting XML node at specific position

I have an XML file and I am loading it in Xmldocument. This document has a node with some child nodes like this

<xml here>
   <child> </child>
   <children></children>  // I need to insert it
   <children></children>  // I need to insert this second time
   <child> </child>
<xml here>

here somenode has some children where first and last children node names are same where as other nodes except the first and last node has some diffrent name ( identical to each other ). I am creating a function to insert a node at specific position, I am not sure about the criteria but may be in the mid.
  • how can I insert node in specific position. I am using XMLnode.appendChild method for insertion
  • Do I need to rearrange/sort nodes after insertion. Please suggest.
  • How can I determine what is structure and how should I find where the new node should be added according to current document structure.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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)
    if (index < 0)
        index = 0;

    var childNodes = node.ChildNodes;
    var childrenCount = childNodes.Count;

    if (index >= childrenCount)

    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);

Method 2

you can use XLinq to modify XML document

Following is an example of xml modification

    String xmlString = "<?xml version="1.0"?>"+"<xmlhere>"+
    " <child> </child>"+
    " <children>1</children>"+ //1
    " <children>2</children>"+ //2
    " <children>3</children>"+ // 3, I need to insert it
    " <children>4</children>"+  //4,  I need to insert this second time
    " <children>5</children>"+
    " <children>6</children>"+ 
    " <child> </child>"+
    " </somenode>"+

    XElement root = XElement.Parse(xmlString);
    var childrens = root.Descendants("children").ToArray();
    var third = childrens[3];
    var fourth = childrens[4];
    third.AddBeforeSelf(new XElement("children"));
    fourth.AddBeforeSelf(new XElement("children"));

    var updatedchildren = root.Descendants("children").ToArray();

Method 3
Cheack it!I guess it will help u.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x