开发者

Serialize List<T> to XML, and reverse the XML to List<T>

Does anyone know how I (or if it's possible to) reverse the XML I'm creating below

[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;
    }

    pu开发者_开发百科blic static StringWriter Serialize(object o)
    {
        var xs = new XmlSerializer(o.GetType());
        var xml = new StringWriter();
        xs.Serialize(xml, o);

        return xml;
    }
}

The xml rendered

<?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>

Now, after a few hours of Googling and trying I'm stuck (most likely my brain have some vacation already). Can anyone help me how to reverse this xml back to a List?

Thanks


Just deserialize it:

public static T Deserialize<T>(string xml) {
  var xs = new XmlSerializer(typeof(T));
  return (T)xs.Deserialize(new StringReader(xml));
}

Use it like this:

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


XmlSerializer.Deserialize

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜