Enforces that parent has exactly 1 child of type XML element and nothing else (barring comments and whitespaces) and returns the child - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Enforces that parent has exactly 1 child of type XML element and nothing else (barring comments and whitespaces) and returns the child

Demo Code

// The .NET Foundation licenses this file to you under the MIT license.
using System.Xml;
using System.Text;

public class Main{
        internal static XmlElement GetChildElement(XmlElement parent, string childLocalName, string childNamespace)
        {/*w  w w  .  j a  v  a 2s. c o  m*/
            if (parent == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
            }

            for (int i = 0; i < parent.ChildNodes.Count; ++i)
            {
                XmlNode child = parent.ChildNodes[i];

                if (child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.Comment)
                {
                    continue;
                }
                else if (child.NodeType == XmlNodeType.Element)
                {
                    if (child.LocalName == childLocalName && child.NamespaceURI == childNamespace)
                    {
                        return ((XmlElement)child);
                    }
                }
                else
                {
                    OnUnexpectedChildNodeError(parent, child);
                }
            }

            return null;
        }
        /// <summary>
        /// Enforces that parent has exactly 1 child of type XML element and nothing else (barring comments and whitespaces)
        /// and returns the child
        /// </summary>
        internal static XmlElement GetChildElement(XmlElement parent)
        {
            if (parent == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
            }

            XmlElement result = null;
            for (int i = 0; i < parent.ChildNodes.Count; ++i)
            {
                XmlNode child = parent.ChildNodes[i];
                if (child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.Comment)
                {
                    continue;
                }
                else if (child.NodeType == XmlNodeType.Element && result == null)
                {
                    result = ((XmlElement)child);
                }
                else
                {
                    OnUnexpectedChildNodeError(parent, child);
                }
            }

            if (result == null)
            {
                OnChildNodeTypeMissing(parent, XmlNodeType.Element);
            }

            return result;
        }
}

Related Tutorials