[英]c# - change ElementName
我有以下课程:
[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”。 在此先感谢您的协助。
我想动态更改Item的ElementName
.NET中的属性确实不是为此设计的。 想法是它们是编译时元数据。 如果需要更多动态元数据,则需要采用其他方法。
在这种情况下,我建议您手动编写XML序列化(使用LINQ to XML常常很容易),或者只执行写入后和读取前的转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.