Generic Method to Get an Element value of XML Document
1. Generic Method
2. Method Call
3.Sample XML
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
Post a Comment