首頁 > 後端開發 > C++ > 如何使用 C# 用 XML 資料填入字典?

如何使用 C# 用 XML 資料填入字典?

Susan Sarandon
發布: 2025-01-04 00:01:42
原創
642 人瀏覽過

How to Populate a Dictionary with XML Data Using C#?

填充字典帶有XML 資料

給定一個空字典和自訂XML,格式為:

<items>
  <item>
登入後複製

要使用XML 中的資料填充字典並將其序列化回來,我們將使用自訂類別和XmlSerializer 類別。

序列化使用自訂類別

  1. 定義自訂類別以充當XML 的臨時容器data:
public class item
{
    [XmlAttribute]
    public int id;
    [XmlAttribute]
    public string value;
}
登入後複製
  1. 使用適當的root 和type 屬性建立XmlSerializer實例:
XmlSerializer serializer = new XmlSerializer(typeof(item[]), 
                                 new XmlRootAttribute() { ElementName = "items" });
登入後複製
  1. 透過轉換來序列化字典到項目物件陣列並序列化array:
serializer.Serialize(stream, 
              dict.Select(kv=>new item(){id = kv.Key,value=kv.Value}).ToArray() );
登入後複製

使用自訂類別反序序列化

  1. 將XML反序列化為項目物件陣列:
var orgDict = ((item[])serializer.Deserialize(stream))
               .ToDictionary(i => i.id, i => i.value);
登入後複製

取代: 使用XElement

如果您喜歡使用XElement class:

使用XElement 進行序列化

  1. 建立表示XML 結構的XElement物件:
XElement xElem = new XElement(
                    "items",
                    dict.Select(x => new XElement("item",new XAttribute("id", x.Key),new XAttribute("value", x.Value)))
                 );
var xml = xElem.ToString(); //xElem.Save(...);
登入後複製

使用XElement 進行反序列化

  1. 將XML 解析為XElement物件:
XElement xElem2 = XElement.Parse(xml); //XElement.Load(...)
登入後複製
  1. 使用LINQ 從XML中擷取資料並填入字典:
var newDict = xElem2.Descendants("item")
                    .ToDictionary(x => (int)x.Attribute("id"), x => (string)x.Attribute("value"));
登入後複製

以上是如何使用 C# 用 XML 資料填入字典?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板