Home > database >  How to get the value of AttributeName of XMLAttribute of object C#
How to get the value of AttributeName of XMLAttribute of object C#

Time:10-14

I want to use reflection to get the AttributeName of an XMLAttribute.

public class Rate{
    [XmlAttribute(AttributeName = "roomcode")]
    public string Code { get; set; }
}

When I do:

var rate = typeof(Rate).GetProperty("Code").GetCustomAttributes(true);

I can see that there is a property on the object rate with AttributeName "roomcode", but no matter what I try, I can't seem to access it.

enter image description here

I want to do a unit test where I compare the attributenames on my object to the attributenames of an xml node.

CodePudding user response:

GetCustomAttributes returns an object[], so you need to cast to XmlAttributeAttribute to access the AttributeName property.

One way would be to use LINQ Cast and Single:

var rate = typeof(Rate)
    .GetProperty("Code")
    .GetCustomAttributes(true)
    .Cast<XmlAttributeAttribute>()
    .Single()
    .AttributeName;

But it would be more concise to use the GetCustomAttribute<T> extension method, which obtains a single attribute of the given type T:

var rate = typeof(Rate)
    .GetProperty("Code")
    .GetCustomAttribute<XmlAttributeAttribute>(true)
    .AttributeName;

As an aside, you could also use nameof when obtaining the PropertyInfo to improve type safety:

var rate = typeof(Rate)
    .GetProperty(nameof(Rate.Code))
    .GetCustomAttribute<XmlAttributeAttribute>(true)
    .AttributeName;
  • Related