For example I want to remove or change below property attributes or add a new one. Is it possible?
[XmlElement("bill_info")]
[XmlIgnore]
public BillInfo BillInfo
{
get { return billInfo; }
set { billInfo = value; }
}
For example I want to remove or change below property attributes or add a new one. Is it possible?
[XmlElement("bill_info")]
[XmlIgnore]
public BillInfo BillInfo
{
get { return billInfo; }
set { billInfo = value; }
}
(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.
It is not possible to add/remove attributes from a class at runtime.
It is possible however to update the way XML serialization works at runtime without needing to edit attributes. See Marc's post.
EDIT Updated