我想在XDocument中搜索SerializableClass
内部的SerializableClass
。如果typeof(SerializableClass).Name
具有XmlRoot属性,则其名称将不同于{{1}}。如何查找此类的XmlRoot属性?
答案 0 :(得分: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;
}
}