tags:

views:

156

answers:

2

I have a class with a few basic properties...

[XmlAttribute("MyFirstProperty")]
public string FirstProperty { get; set; }

[XmlAttribute("MySecondProperty")]
public string SecondProperty { get; set; }

Using Reflection, I can enumerate through the public properties and get PropertyInfo objects for each of the properties above... the only thing I need now is a way to:

  1. Detect whether or not the property has a XmlAttribute (I'm thinking this works via PropertyInfo.IsDefined(typeof(XmlAttribute), true) but would like to make sure)
  2. Get the string value of the XmlAttribute

How is this done?

+4  A: 
 object[] attribs = myPropertyInfo.GetCustomAttributes(typeof(XmlAttribute),false);
 bool doesPropertyHaveAttrib =attribs.Length > 0; 
 string name = (XmlAttribute)(attribs[0].AttributeName);

Good point by Joel in the comments. My bad. Fixed.

BFree
You're going to have to do some casting on that last line. System.Object doesn't have an AttributeName property.
Joel Mueller
The easiest "fix" is to use Attribute[] attribs = Attribute.GetAttributes(myPropertyInfo, typeof(XmlAttribute));
Marc Gravell
A: 

I currently use this approach:

'Get the properties

       Dim pi() As PropertyInfo = arguments.SourceObject.GetType.GetProperties(BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public Or BindingFlags.GetProperty)

'get attributes for the properties

dim pitem As PropertyInfo=pi(0)

           Dim vobj() As Object = pitem.GetCustomAttributes(GetType(ValidationSettingsBaseAttribute), False)


          Dim attr As ValidationSettingsBaseAttribute= TryCast(vobj(0), ValidationSettingsBaseAttribute)
eschneider