c# change ElementName

I have the following class:

 [Serializable]
public class UniversalRequest
{
    [XmlElement(ElementName ="TEMP")]
    public string Item { get; set; }
}

and I would like to change the ElementName of Item dynamically.

I tried the following but unsuccessfully:

foreach (PropertyInfo property in GetType().GetProperties())
{
    if (property.Name.Equals("Item"))
    {
        var attr = from a in (property.GetCustomAttributes(true))
                   where (a.GetType() == typeof(XmlElementAttribute))
                   select a;

        var xmlElementAttribute = (XmlElementAttribute)attr.SingleOrDefault();
        if (xmlElementAttribute != null)
            xmlElementAttribute.ElementName = "NEWITEMNAME";


    }
}

seems like the ElementName has been set to the new value but it back to be "TEMP" on the next iteration. thanks in advance for any assistance.

Jon Skeet
people
quotationmark

I would like to change the ElementName of Item dynamically

Attributes in .NET really aren't designed for that. The idea is that they're compile-time metadata. If you want more dynamic metadata, you'll need to take a different approach.

In this case, I'd suggest either writing your XML serialization manually (which is often pretty easy with LINQ to XML) or just performing a transformation post-write and pre-read.

people

See more on this question at Stackoverflow