Inserts a 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 a XML node at the specified segment if it doesn't exist, otherwise traverses the node.

Demo Code


using System.Diagnostics;
using System.Collections.Specialized;
using System.Xml;
using System.Data;
using System;/* w w  w  .  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>
      public 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