簡體   English   中英

C#-更改ElementName

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM