You can do this to get the XPathAttribute
associated with a property:
var attr = (XPathAttribute)typeof(Appointment)
.GetProperty("Id")
.GetCustomAttributes(typeof(XPathAttribute), true)[0];
You could wrap this in a method using an Expression
like this:
public static string GetXPath<T>(Expression<Func<T>> expr)
{
var me = expr.Body as MemberExpression;
if (me != null)
{
var attr = (XPathAttribute[])me.Member.GetCustomAttributes(typeof(XPathAttribute), true);
if (attr.Length > 0)
{
return attr[0].Value;
}
}
return string.Empty;
}
And call it like this:
Appointment appointment = new Appointment();
GetXPath(() => appointment.Id) // appt/@id
Or if you prefer to be able to call this without having an object instance to reference:
public static string GetXPath<T, TProp>(Expression<Func<T, TProp>> expr)
{
var me = expr.Body as MemberExpression;
if (me != null)
{
var attr = (XPathAttribute[])me.Member.GetCustomAttributes(typeof(XPathAttribute), true);
if (attr.Length > 0)
{
return attr[0].Value;
}
}
return string.Empty;
}
And call it like this:
GetXPath<Appointment>(x => x.Id); // appt/@id