Determines whether the specified location can be created in the specified XML element. - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Determines whether the specified location can be created in the specified XML element.

Demo Code


using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Xml.Linq;
using System;/*w  w  w  .  ja  va2  s.co m*/

public class Main{
        /// <summary>
        /// Determines whether the specified location can be created in the specified XML element.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <returns>
        /// <c>true</c> if the specified location can be created in the specified XML element; otherwise, <c>false</c>.
        /// </returns>
        public static bool CanCreateLocation(XElement baseElement, string location)
        {
            var locSteps = location.SplitPathNamespaceSafe();

            XElement currentLocation = baseElement;
            foreach (string loc in locSteps)
            {
                if (loc == ".")
                {
                    continue;
                }
                else if (loc == "..")
                {
                    currentLocation = currentLocation.Parent;
                    if (currentLocation == null)
                        return false;
                }
                else
                {
                    XName curLocName = loc;
                    if (curLocName.Namespace.IsEmpty())
                        currentLocation = currentLocation.Element(curLocName);
                    else
                        currentLocation = currentLocation.Element_NamespaceNeutral(curLocName);

                    if (currentLocation == null)
                        return true;
                }
            }

            return true;
        }
        public static bool IsEmpty(this XNamespace self)
        {
            return self != null && !String.IsNullOrEmpty(self.NamespaceName.Trim());
        }
        public static XElement Element_NamespaceNeutral(this XContainer parent, XName name)
        {
            return parent.Elements().FirstOrDefault(e => e.Name.LocalName == name.LocalName);
        }
}

Related Tutorials