简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM