XmlElement reflect
本文关键字:reflect XmlElement | 更新日期: 2023-09-27 17:56:23
像这两个类
[XmlRoot("Root")]
public class VcRead
{
[XmlElement("item")]
public string[] Items;
[XmlElement("amount")]
public int Count;
}
public class KeyItem
{
[XmlAttribute("id")]
public int ID;
[XmlAttribute("name")]
public string Title;
}
现在,我想使用反射来获取所有字段及其 Xml 标记。获取字段的名称及其值很容易。但是,如何获取 XmlElement 的值,例如"金额"
[XmlElement("amount")]
public int Count;
Type type = typeof(VcRead);
foreach (var fiedInfo in type.GetFields())
{
// your field
foreach (var attribute in fiedInfo.GetCustomAttributes(true))
{
// attributes
}
}
要从XmlElementAttribute
获取元素名称(与XmlAttributeAttribute
的方法相同):
if (attribute is XmlElementAttribute)
{
var elementName = ((XmlElementAttribute)attribute).ElementName;
}
另请记住,您的类具有公共字段而不是属性。
而不是 XmlElement,使用 XmlElementAttribute,如下所示
[XmlElementAttribute("test")]
public string Test {get;set;};
然后,通过反射访问此对象的 GetProperties()
PropertyInfo[] methods = typeof(KeyItem).GetProperties();
foreach (PropertyInfo method in methods)
{
// Use of Attribute.GetCustomAttributes which you can access the attributes
Attribute[] attribs = Attribute.GetCustomAttributes(method, typeof(XmlAttribute));
}