C# XmlElement反射
像这两门课C# XmlElement反射,c#,.net,C#,.net,像这两门课 [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")]
[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的值,例如
要从xmlementattribute
获取元素名称(与XmlAttributeAttribute
的方法相同):
还要记住,您的类具有公共字段而不是属性。使用XmlElement属性而不是XmlElement,如下所示
[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));
}
PropertyInfo类型的GetCustomAttributes方法?
if (attribute is XmlElementAttribute)
{
var elementName = ((XmlElementAttribute)attribute).ElementName;
}
[XmlElementAttribute("test")]
public string Test {get;set;};
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));
}