![](/img/trans.png)
[英]How to convert xml attribute to custom object during deserialization in C# using XmlSerializer
[英]How to change xml attribute while deserialization with xmlserializer c#?
使用 XmlSerializer 反序列化 xml 時有什么方法可以修改屬性值?
例如,我有這樣的 xml:
<chunkList>
<chunk id="ch1" type="p">
<sentence id="s1">
<tok>
<orth>XXX</orth>
<lex disamb="1">
<base>XXX</base>
<ctag>subst:sg:nom:f</ctag>
</lex>
</tok>
</sentence>
</chunk>
</chunkList>
我想將chunk
元素反序列化為Chunk
class 並將屬性id="ch1"
設置為Id
屬性 - 有沒有辦法修剪這個ch
substring 並將數字1
分配給 int 類型的屬性?
[XmlAttribute("id")] //maybe there is some attribute to achive this?
public int Id { get; set; }
我已經閱讀了一些MSDN文檔,但沒有找到任何解決方案。
沒有優雅的方法可以使用單個屬性來實現這一點。 我知道實現所需結果的唯一方法是使用 [XmlIgnore] 並專門為字符串化的 xml ID 創建第二個屬性,並為您的內部 integer 值創建一個本地化的轉換器屬性。 一些沿線:
[XmlAttribute("id")]
public string _id_xml {get; set;}
[XmlIgnore]
public int Id {
// convert local copy of xml attribute value to/from int.
get => int.Parse(_id_xml.Replace("ch",""));
set => _id_xml = $"ch{value}";
}
我的轉換器非常基礎,顯然您需要改進它並考慮錯誤處理。
序列化程序將照常對 [XmlAttribute] 進行操作,但會通過 [XmlIgnore]。 您的 c# 代碼可以使用其中任何一個。 不幸的是,XmlSerializer 需要公共屬性,因此您無法從代碼中隱藏_id_xml屬性,但您可以使用 [Obsolete] 在編譯器中發出警告信號。
您可以使用 _id_xml getter & setter 與 int 進行轉換,但在序列化期間管理錯誤時這樣做可能會出現問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.