Inserts XML node at the specified segment if it doesn't exist, otherwise traverses the node. - CSharp System.Xml

CSharp examples for System.Xml:XML Node

Description

Inserts XML node at the specified segment if it doesn't exist, otherwise traverses the node.

Demo Code

// All rights reserved.
using System.Diagnostics;
using System.Collections.Specialized;
using System.Xml;
using System.Data;
using System;/*from www  . ja v  a  2  s .co m*/

public class Main{
        #endregion

        #region Helpers
        /// <summary>
        /// Inserts a node at the specified segment if it doesn't exist, otherwise
        /// traverses the node.
        /// </summary>
        /// <param name="node">The current node.</param>
        /// <param name="segments">The path segment list.</param>
        /// <param name="idx">The current segment.</param>
        /// <returns></returns>
        protected static XmlNode InsertNode(XmlNode node, string[] segments, int idx)
        {
            XmlNode newNode = null;

            if (idx == segments.Length)
            {
                // All done.
                return node;
            }

            // Traverse the existing hierarchy but ensure that we create a 
            // new record at the last leaf.
            if (idx + 1 < segments.Length)
            {
                foreach (XmlNode child in node.ChildNodes)
                {
                    if (child.Name == segments[idx])
                    {
                        newNode = InsertNode(child, segments, idx + 1);
                        return newNode;
                    }
                }
            }
            XmlDocument doc = node.OwnerDocument;
            newNode = doc.CreateElement(segments[idx]);
            node.AppendChild(newNode);
            XmlNode nextNode = InsertNode(newNode, segments, idx + 1);
            return nextNode;
        }
}

Related Tutorials