Get XML Attribute As Enum - CSharp System.Xml

CSharp examples for System.Xml:XML Attribute

Description

Get XML Attribute As Enum

Demo Code

// This is free software licensed under the NUnit license. You may
using System.Xml;
using System.Collections.Generic;
using System;//from  www  .  jav a  2s.c  om

public class Main{
        public static T GetAttributeAsEnum<T>(XmlNode node, string name, T defaultValue)
        {
            string attrVal = XmlHelper.GetAttribute(node, name);
            if (attrVal == null)
                return defaultValue;

            if (typeof(T).IsEnum)
            {
                foreach (string s in Enum.GetNames(typeof(T)))
                    if (s.Equals(attrVal, StringComparison.OrdinalIgnoreCase))
                        return (T)Enum.Parse(typeof(T), attrVal, true);
            }

            throw new XmlException(
                string.Format("Invalid attribute value: {0}", node.Attributes[name].OuterXml));
        }
        #region Attributes

        public static string GetAttribute(XmlNode node, string name)
        {
            XmlAttribute attr = node.Attributes[name];
            return attr == null ? null : attr.Value;
        }
}

Related Tutorials