Lire et Convertir un attribut à partir d’un XmlElement

Author:

Utilisation,de,la,classe,'XmlTextReader',pour,lire,un,document,XML
{filelink=16405}

/*
 http://validationframework.codeplex.com/
 License:  Microsoft Permissive License (Ms-PL) v1.1
 */
using System;
using System.Xml;

namespace ValidationFramework.Extensions
{
    public static class XmlElementExtensions
    {
        ///

        /// Attempts to get and convert an attribute from a . If the item does not exist or can't be converted a
 is returned.
        /// 

        /// 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
 if
 exists; otherwise
.
        internal static T GetAttribute(this XmlElement element, string key, T defaultValue)
        {
            if (!element.HasAttribute(key))
                return defaultValue;

            var stringValue = element.GetAttribute(key);

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

            if (!converter.CanConvertFrom(typeof(string)))
                return defaultValue;

            return (T)converter.ConvertFromString(stringValue);
        }

    }
}

Leave a Reply

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