2011-07-04 1 views
8

Est-ce que quelqu'un sait comment je (ou s'il est possible de) inverser le XML que je crée ci-dessoussérialisation Liste <T> à XML, et inverser le XML à la liste <T>

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

Le xml rendu

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

Maintenant, après quelques heures de googling et d'essayer je suis coincé (très probablement mon cerveau a déjà des vacances). Quelqu'un peut-il m'aider à inverser ce xml à une liste?

Merci

+0

nouvelle Désérialise (.. XmlSerializer (o.GetType()). .) –

+0

Avez-vous vraiment besoin d'un dictionnaire personnalisé? Le dictionnaire générique peut avoir n'importe quel type comme clé et valeur. –

Répondre

14

Juste désérialiser:

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

utiliser comme ceci:

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