Generic Method to Get an Element value of XML Document

1. Generic Method

  public static T GetElementValue<T>(this XElement element)  
     {  
       if (element == null)  
         return default(T);  
       if (string.IsNullOrEmpty(element.Value))  
         return default(T);  
       if (typeof(T) == typeof(string))  
         return (T)Convert.ChangeType(element.Value, typeof(T));  
       PropertyInfo[] properties = typeof(T).GetProperties();  
       Type underlyingType = typeof(T);  
       if (properties.Count() == 2 &&  
         string.Equals(properties[0].Name, "HasValue", StringComparison.InvariantCultureIgnoreCase))  
         underlyingType = properties[1].PropertyType;  
       MethodInfo method = underlyingType.GetMethod("Parse", new[] { typeof(string) });  
       var newObject = (T)method.Invoke(null, new object[] { element.Value });  
       return newObject;  
     }  

2. Method Call

 var xElement = XElement.Load("Data.xml");  
 var siteUrl = xElement.Element("SiteURL").GetElementValue<string>();  
 var userName = xElement.Element("UserName").GetElementValue<string>()  


3.Sample XML

 <?xml version="1.0" encoding="utf-8" ?>  
 <SiteInformation>  
    <SiteURL> http://www.google.com</SiteURL>  
    <UserName>User123</UserName>  
 </SiteInformation>  

Comments

Popular posts from this blog

Deep dive into OpenXML Part 1

Deep dive into OpenXML Part 2

Convert XML data to dynamic (ExpandoObject) Object