列出具有给定 class 的 [XmlAttribute] 的所有属性

list all properties with [XmlAttribute] of given class

例如我有一个简单的class

class SomeCfg
{
    [XmlAttribute("ArchivePath")]
    public string ArchivePath { get; set; }
}

可以看出 class 有一个 属性 具有 Xml 属性 。但是当程序执行到那个代码时

 var t = typeof (SomeCfg);
 var props = t.GetProperties().Where(
    prop => Attribute.IsDefined(prop, typeof(XmlAttribute)));

运行时抛出异常

System.ArgumentException: Type passed in must be derived from System.Attribute or System.Attribute itself.

当然,当我看到类型层次结构时,我意识到这是真的(我不会讨论为什么它不继承那个 class)。

我的问题是如何列出这些属性(在这种情况下,创建继承自 Xml 属性和 System.Attribute 的 class 不是一个选项)。

根据问题标签.Net 版本是 4.0。

有没有可能你使用了System.Xml.XmlAttribute instead of System.Xml.Serialization.XmlAttributeAttribute

System.Xml.XmlAttribute 用于表示 xml 文档中的属性。 System.Xml.Serialization.XmlAttributeAttribute 指定 XmlSerializer 必须将 class 成员序列化为 XML 属性。

您可以从以下代码中获取包含 XMLAttribute 的属性..

var props = t.GetProperties()
             .Where(prop =>
                 prop.GetCustomAttributes(typeof(XmlAttributeAttribute), false).Any(PropType => PropType.GetType() == typeof(XmlElementAttribute) ||
                                                         PropType.GetType() == typeof(XmlAttributeAttribute)));

如果您不想使用完整的 LINQ 那么这个 post 对您也有帮助。

Serialize all properties in a class as attributes instead of elements