将 List<T> 序列化为 XML,并将 XML 反序列化为 List<T>。

8
有人知道如何(或是否可能)反转我下面创建的XML吗?
[Serializable()]
public class CustomDictionary
{
    public string Key { get; set; }
    public string Value { get; set; }
}

public class OtherClass
{
    protected void BtnSaveClick(object sender, EventArgs e)
    {
        var analysisList = new List<CustomDictionary>();

        // Here i fill the analysisList with some data
        // ...

        // This renders the xml posted below
        string myXML = Serialize(analysisList).ToString();
        xmlLiteral.Text = myXML;
    }

    public static StringWriter Serialize(object o)
    {
        var xs = new XmlSerializer(o.GetType());
        var xml = new StringWriter();
        xs.Serialize(xml, o);

        return xml;
    }
}

XML渲染
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfCustomDictionary xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <CustomDictionary>
    <Key>Gender</Key>
    <Value>0</Value>
  </CustomDictionary>
  <CustomDictionary>
    <Key>Height</Key>
    <Value>4</Value>
  </CustomDictionary>
  <CustomDictionary>
    <Key>Age</Key>
    <Value>2</Value>
  </CustomDictionary>
</ArrayOfCustomDictionary>

现在,经过几个小时的谷歌搜索和尝试后,我卡住了(很可能是我的大脑已经放假了)。有人能帮我将这个xml反转回List吗?
谢谢。

新的 XmlSerializer(o.GetType()).Deserialize(...) - Marek Musielak
你真的需要自定义词典吗?通用字典可以使用任何类型作为键和值。 - Steve Wellens
2个回答

14
只需进行反序列化操作即可:
public static T Deserialize<T>(string xml) {
  var xs = new XmlSerializer(typeof(T));
  return (T)xs.Deserialize(new StringReader(xml));
}

使用方法如下:

var deserializedDictionaries = Deserialize<List<CustomDictionary>>(myXML);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接