gpt4 book ai didi

c# - 将 List 序列化为 XML,并将 XML 反转为 List

转载 作者:太空狗 更新时间:2023-10-29 18:19:10 34 4
gpt4 key购买 nike

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

谢谢

最佳答案

反序列化:

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

关于c# - 将 List<T> 序列化为 XML,并将 XML 反转为 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6572828/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com