Identify XML Serialization rule(s) specified in a class
Is it possible to do the following :
Create an instance of SomeCLass in another part of my code AND Using this newly created instance/object can I obtain the :
[System.Xml.Serialization.XmlElementAttribute("someClass")] XML Serialization rule
What I am Trying To Achieve :
1. Identify whether SomeCLass contains an XML Serialization rule on any property in it 2. If it does contain such a serialization rule, identify the rule. (i.e. whether its an ... XMLIgnore || XMLElement || XMLAttribute ... etc.)The class referred to in the question :
Class SomeClass
{
SomeOtherClass[] privtArr;
[System.Xml.Serialization.XmlElementAttribute("SomeOtherClass")]
public SomeOtherClass[] anInstance
{
get
{
开发者_如何学运维 return this.privtArr;
}
set
{
this.privtArr = value;
}
}
}
You don't need to create an instance; simply look at the Type
, in particular GetFields()
and GetProperties()
. Loop over the public non-static fields/properties, and check Attribute.GetCustomAttribute(member, attributeType)
- i.e.
public class Test
{
[XmlElement("abc")]
public int Foo { get; set; }
[XmlIgnore]
public string Bar { get; set; }
static void Main()
{
var props = typeof (Test).GetProperties(
BindingFlags.Public | BindingFlags.Instance);
foreach(var prop in props)
{
if(Attribute.IsDefined(prop, typeof(XmlIgnoreAttribute)))
{
Console.WriteLine("Ignore: " + prop.Name);
continue; // it is ignored; stop there
}
var el = (XmlElementAttribute) Attribute.GetCustomAttribute(
prop, typeof (XmlElementAttribute));
if(el != null)
{
Console.WriteLine("Element: " + (
string.IsNullOrEmpty(el.ElementName) ?
prop.Name : el.ElementName));
}
// todo: repeat for other interesting attributes; XmlAttribute,
// XmlArrayItem, XmlInclude, etc...
}
}
}
If you do need to create an instance, use new
or Activator.CreateInstance
.
You don't even need to instantiate SomeClass.
use Reflection to list (public) fields and properties of typeof(SomeClass)
.
Then for each field/property, enumerate attributes and filter the ones you are interested in (such as XmlElement()
, XmlAttribute()
,...
Note however that the XmlSerializer
serializes public fields and properties even if they don't have an XmlBlah
attribute. They are serialized unless they are marked as [XmlIgnore()]
. You should then lookup this attribute as well.
Of course, you may also be interested in Xml attributes at the class level.
精彩评论