(edit - I misread the original question)
You cannot add actual attributes (they are burned into the IL); however, with XmlSerializer
you don't have to - you can supply additional attributes in the constructor to the XmlSerializer
. You do, however, need to be a little careful to cache the XmlSerializer
instance if you do this, as otherwise it will create an additional assembly per instance, which is a bit leaky. (it doesn't do this if you use the simple constructor that just takes a Type
). Look at XmlAttributeOverrides
.
For an example:
using System;
using System.Xml.Serialization;
public class Person
{
static void Main()
{
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attribs = new XmlAttributes();
attribs.XmlIgnore = false;
attribs.XmlElements.Add(new XmlElementAttribute("personName"));
overrides.Add(typeof(Person), "Name", attribs);
XmlSerializer ser = new XmlSerializer(typeof(Person), overrides);
Person person = new Person();
person.Name = "Marc";
ser.Serialize(Console.Out, person);
}
private string name;
[XmlElement("name")]
[XmlIgnore]
public string Name { get { return name; } set { name = value; } }
}
Note also; if the xml attributes were just illustrative, then there is a second way to add attributes for things related to data-binding, by using TypeDescriptor.CreateProperty
and either ICustomTypeDescriptor
or TypeDescriptionProvider
. Much more complex than the xml case, I'm afraid - and doesn't work for all code - just code that uses the component-model.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…