1

この2つのようなクラス

[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 マークを取得したいと考えています。フィールドの名前とその値を取得するのは簡単です。しかし、「amount」などの 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 に答える