Inserts a new element as a child of an existing XmlNode and returns it. - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Inserts a new element as a child of an existing XmlNode and returns it.

Demo Code

// This is free software licensed under the NUnit license. You may
using System.Xml;
using System.Collections.Generic;
using System;/*from  w  ww .j a  v a  2 s .  co m*/

public class Main{
        /// <summary>
        /// Inserts a new element as a child of an existing XmlNode and returns it.
        /// </summary>
        /// <param name="node">The node to which the element should be inserted as a child.</param>
        /// <param name="name">The element name.</param>
        /// <param name="index">The index at which the element should be inserted.</param>
        /// <returns>The newly created child element</returns>
        public static XmlNode InsertElement(XmlNode node, string name, int index)
        {
            XmlNode childNode = node.OwnerDocument.CreateElement(name);
            int childCount = node.ChildNodes.Count;

            if (index < 0 || index > childCount)
                throw new ArgumentOutOfRangeException("index");

            if (index == node.ChildNodes.Count)
                node.AppendChild(childNode);
            else
                node.InsertBefore(childNode, node.ChildNodes[index]);

            return childNode;
        }
}

Related Tutorials