C# 序列化列表<;T>;转换为XML,并将XML转换为列表<;T>;
有人知道我是如何(或者如果可能的话)反转我在下面创建的XML的吗C# 序列化列表<;T>;转换为XML,并将XML转换为列表<;T>;,c#,list,serialization,deserialization,C#,List,Serialization,Deserialization,有人知道我是如何(或者如果可能的话)反转我在下面创建的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) {
[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;
}
}
[Serializable()]
公共类自定义词典
{
公共字符串密钥{get;set;}
公共字符串值{get;set;}
}
公共类其他类
{
受保护的无效BtnSaveClick(对象发送方,事件参数e)
{
var analysisList=新列表();
//在这里,我用一些数据填充分析列表
// ...
//这将呈现下面发布的xml
字符串myXML=Serialize(analysisList).ToString();
Text=myXML;
}
公共静态StringWriter序列化(对象o)
{
var xs=新的XmlSerializer(o.GetType());
var xml=new StringWriter();
序列化(xml,o);
返回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>
性别
0
高度
4.
年龄
2.
现在,在谷歌搜索和尝试了几个小时后,我被卡住了(很可能我的大脑已经有假期了)。有谁能帮我把这个xml还原成一个列表吗
谢谢请反序列化它:
public static T Deserialize<T>(string xml) {
var xs = new XmlSerializer(typeof(T));
return (T)xs.Deserialize(new StringReader(xml));
}
publicstatict反序列化(字符串xml){
var xs=新的XmlSerializer(typeof(T));
返回(T)xs.Deserialize(新的StringReader(xml));
}
像这样使用它:
var deserializedDictionaries = Deserialize<List<CustomDictionary>>(myXML);
var deserializedDictionaries=反序列化(myXML);
new XmlSerializer(o.GetType())。反序列化(…)您真的需要自定义词典吗?泛型字典可以有任何类型作为键和值。