将字典(字符串,列表<;字符串>;)序列化为xml

本文关键字:字符串 序列化 xml gt 字典 列表 lt | 更新日期: 2023-09-27 17:53:13

可能重复:
转换字典的简单方法<字符串,字符串>到xml,反之亦然

我有样品类别:

public class SampleClass
{
   public Dictionary<string, List<string>> SampleProperties {get;set;}
}

我想将这个类序列化为xml。我该怎么做?我想要类似于以下示例的输出xml:

<DataItem>
   <key>
      <value></value>
      <value></value>
      <value></value>
   </key>
</DataItem>

问候

将字典(字符串,列表<;字符串>;)序列化为xml

您可以使用Linq到Xml从SampleClass对象创建所需的Xml:

SampleClass sample = new SampleClass();
sample.SampleProperties = new Dictionary<string, List<string>>() {
    { "Name", new List<string>() { "Greg", "Tom" } },
    { "City", new List<string>() { "London", "Warsaw" } }
};
var result = new XElement("DataItem", 
                 sample.SampleProperties.Select(kvp =>
                    new XElement(kvp.Key, 
                      kvp.Value.Select(value => new XElement("value", value)))));
result.Save(path_to_xml);

输出:

<DataItem>
   <Name>
      <value>Greg</value>
      <value>Tom</value>
   </Name>
   <City>
      <value>London</value>
      <value>Warsaw</value>
   </City>
</DataItem>

从xml反序列化:

SampleClass sample = new SampleClass();
sample.SampleProperties = XElement.Load(path_to_xml).Elements().ToDictionary(
                              e => e.Name.LocalName,
                              e => e.Elements().Select(v => (string)v).ToList());

尝试以下代码片段

var dict = new Dictionary<string, List<string>>();
dict.Add("a1", new List<string>(){"a1","a2","a3"});
XElement root = new XElement("DataItem");
foreach(var item in dict)
{
  XElement element = new XElement("Key",item.Key);
  item.Value.ForEach (x => element.Add (new XElement("Value",x)));
  root.Add(element);
}