2011-01-28 32 views
1

我想搜索一個XDocument,其中出現SerializableClass。當SerializableClass具有XmlRoot屬性時,它將具有與typeof(SerializableClass).Name不同的名稱。我怎樣才能查找這個類的XmlRoot屬性?獲取某類的XmlRoot

回答

2

你的意思是你想要找到用於表示XML中某個元素的類的名稱?

這是我要做的事:

/// <summary> 
     /// Determines and returns the name of the XmlElement that should represent instances of the given type 
     /// in an XML stream. 
     /// </summary> 
     /// <param name="serializedObjectType"></param> 
     /// <returns></returns>   
     [SuppressMessage ("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] 
     public static string GetRootNodeElementNameForType(Type serializedObjectType) 
     { 
      // Determine if the Type contains an XmlRoot Attribute. If so, the XmlRoot attribute should contain 
      // the name of the element-name for this type. 
      // Otherwise, the name of the type should 've been used for serializing objects of this type. 
      XmlRootAttribute theAttrib = Attribute.GetCustomAttribute (serializedObjectType, typeof (XmlRootAttribute)) as XmlRootAttribute; 

      if(theAttrib != null) 
      { 
       if(String.IsNullOrEmpty (theAttrib.ElementName) == false) 
       { 
        return theAttrib.ElementName; 
       } 
       else 
       { 
        return serializedObjectType.Name; 
       } 
      } 
      else 
      { 
       return serializedObjectType.Name; 
      } 
     } 
+1

==假的?暴行! :D – 2011-01-28 15:03:49