【问题标题】:Serialize List<T> to XML, and reverse the XML to List<T>将 List<T> 序列化为 XML,并将 XML 反转为 List<T>
【发布时间】:2011-09-28 04:57:11
【问题描述】:

有谁知道我如何(或者如果可能的话)反转我在下面创建的 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 反转回列表?

谢谢

【问题讨论】:

  • new XmlSerializer(o.GetType()).Deserialize(...)
  • 您真的需要自定义词典吗?通用字典可以有任何类型作为键和值。

标签: c# list serialization deserialization


【解决方案1】:

只需反序列化它:

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);

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 2012-04-06
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多