[英]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. 并且我想动态更改Item的ElementName。
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. 似乎ElementName已设置为新值,但在下一次迭代时又恢复为“ TEMP”。 thanks in advance for any assistance.
在此先感谢您的协助。
I would like to change the ElementName of Item dynamically
我想动态更改Item的ElementName
Attributes in .NET really aren't designed for that. .NET中的属性确实不是为此设计的。 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. 在这种情况下,我建议您手动编写XML序列化(使用LINQ to XML常常很容易),或者只执行写入后和读取前的转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.