Returns the attribute value as a specific type - CSharp System.Xml

CSharp examples for System.Xml:XML Attribute

Description

Returns the attribute value as a specific type

Demo Code


using System.Xml;
using System.Text;
using System;//  w w w . j  a  v a 2  s.  c  om

public class Main{
        /// <summary>
        /// Returns the attribute value as a specific type
        /// </summary>
        /// <param name="rXML">string that holds the attributes</param>
        /// <param name="rName">Name of the attribute to retrieve</param>
        /// <returns></returns>
        public static string GetAttribute(string rXML, string rName)
        {
            int lStart = rXML.IndexOf("t=\"");
            if (lStart >= 0)
            {
                int lEnd = rXML.IndexOf("\"", lStart + 3);
                if (lEnd >= 0)
                {
                    return rXML.Substring(lStart + 3, lEnd - (lStart + 3));
                }
            }

            return "";
        }
        /// <summary>
        /// Returns the attribute value as a specific type
        /// </summary>
        /// <typeparam name="T">Type to return</typeparam>
        /// <param name="rXML">XmlNode that holds the attributes</param>
        /// <param name="rName">Name of the attribute to retrieve</param>
        /// <returns></returns>
        public static T GetAttribute<T>(XmlNode rXML, string rName)
        {
            T lValue = default(T);
            if (rXML == null) { return lValue; }

            XmlElement lElement = (XmlElement)rXML;
            if (!lElement.HasAttribute(rName)) { return lValue; }

            string lStringValue = lElement.GetAttribute(rName);
            lValue = (T)Convert.ChangeType(lStringValue, typeof(T));

            return lValue;
        }
}

Related Tutorials