序列表< T>为XML,并扭转XML列出< T> [英] Serialize List<T> to XML, and reverse the XML to List<T>

查看:201
本文介绍了序列表< T>为XML,并扭转XML列出< 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;
    }

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

        return xml;
    }
}



渲染的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>

现在,谷歌搜索了几个小时后,并试图我卡(最有可能我的大脑有一定的休假的话)。谁能帮助我如何扭转这种XML回到一个列表?

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?

感谢

推荐答案

只是反序列化:

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

这篇关于序列表&LT; T&GT;为XML,并扭转XML列出&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆