Example #1
0
 public void GetParentPathTests()
 {
     Assert.Null(ConfigurationPath.GetParentPath(null));
     Assert.Null(ConfigurationPath.GetParentPath(""));
     Assert.Equal("::", ConfigurationPath.GetParentPath(":::"));
     Assert.Equal("a::b::", ConfigurationPath.GetParentPath("a::b:::c"));
     Assert.Equal("a:::b", ConfigurationPath.GetParentPath("a:::b:"));
     Assert.Null(ConfigurationPath.GetParentPath("key"));
     Assert.Equal("", ConfigurationPath.GetParentPath(":key"));
     Assert.Equal(":", ConfigurationPath.GetParentPath("::key"));
     Assert.Equal("parent", ConfigurationPath.GetParentPath("parent:key"));
 }
        } /* End of Function - CreateXmlWriter */

        /*----------------------- GetXmlItem ------------------------------------*/
        /// <summary>
        /// Gets an <see cref="XmlItem"/> for the specified configuraion path/value.
        /// </summary>
        /// <param name="root">
        /// Required root item to search in
        /// </param>
        /// <param name="path">
        /// Path as defined by <see cref="ConfigurationPath"/> syntax.
        /// </param>
        /// <param name="value">
        /// Optional value for the item.
        /// </param>
        protected virtual XmlItem GetXmlItem(
            ref XmlItem root,
            string path,
            string value)
        {
            XmlItem retval = null;
            XmlItem parent = null;


            if (string.IsNullOrEmpty(path))
            {
                throw new InvalidOperationException(
                          $"{nameof(path)} must be a valid configuraiton path.");
            }

            // Parse the parent path from the key, if any
            var parentPath = ConfigurationPath.GetParentPath(path);
            // And get the current key
            var key = ConfigurationPath.GetSectionKey(path);

            // If we do not have a parent, then we will assume the root item as our
            // parent.
            if (null == parentPath)
            {
                parent = root;
            }
            // Otherwise, fetch the parent XML node
            else
            {
                parent = GetXmlItem(ref root, parentPath, null);
            }

            // At this point, we can look for a child in the parent that already
            // matches our key
            retval = parent.Children.Where(v => v.Name == key).SingleOrDefault();

            // If we didn't find one, will create and add to the parent's
            // children.
            if (null == retval)
            {
                retval = new XmlItem(key, value, parent);
                parent.Children.Add(retval);
            } // end of if - child doesn't exist yet
            // Otherwise, if we have a valid value, then we will update at this point
            else if (null != value)
            {
                retval.Value = value;
            }

            return(retval);
        } /* End of Function - GetXmlItem */