c# - 更改ElementName

时间:2014-03-30 14:53:32

标签: c# xml

我有以下课程:

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

我想动态更改Item的ElementName。

我尝试了以下但未成功:

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";


    }
}

似乎已将ElementName设置为新值,但在下一次迭代时它将恢复为“TEMP”。 提前感谢您的任何帮助。

1 个答案:

答案 0 :(得分:2)

  

我想动态更改Item的ElementName

.NET中的属性实际上并不是为此而设计的。这个想法是他们编译时元数据。如果您想要更多动态元数据,则需要采用不同的方法。

在这种情况下,我建议手动编写XML序列化(使用LINQ to XML通常很容易)或者只是在写入和预读后执行转换。