Faire le ‘cast’ de la valeur d’un attribut lu à partir d’un ‘XmlElemen’



  License:  Microsoft Permissive License (Ms-PL) v1.1
using System;
using System.Xml;

namespace ValidationFramework.Extensions
    public static class XmlElementExtensions

        /// Attempts to get and cast attribute from a . If the item does not exist or can't be casted exceptions are thrown.

        /// The  to try to convert to.
The  to extract the attribute value from.
The key to use or the extraction
The default value if
 is not found.
        /// The value from
 exists; otherwise
        internal static T GetAttribute(this XmlElement element, string key)
            if (!element.HasAttribute(key))
                throw new ArgumentOutOfRangeException(string.Format("The key '{0}' cannot be found in xml element.", key));

            var stringValue = element.GetAttribute(key);

            var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));

            return (T)converter.ConvertFromString(stringValue);

Leave a Reply

Your email address will not be published. Required fields are marked *