1

像这两个类

[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;
4

2 回答 2

1
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;
}

另请记住,您的类具有公共字段而不是属性。

于 2013-01-29T09:39:46.677 回答
1

而不是 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));
 }
于 2013-01-29T10:16:31.650 回答