2010-11-29 5 views
4

J'ai la classe suivante et je suis en train de sérialisation et la désérialisation de et vers un fichier XML:C# deserialize fichier xml pour former Liste <T>

public class cUrlData 
{ 
    public string ProgramName {get;set;} 
    public string ExeName { get; set; } 
    public string Category { get; set; } 
    public string URL { get; set; } 

    public cUrlData() 
    { 
    } 

    public void Add(string ProgramName, string ExeName, string Category, string ProgramURL) 
    { 
     this.ProgramName = ProgramName; 
     this.ExeName = ExeName; 
     this.URL = ProgramURL; 
     this.Category = Category; 
    } 

} 

J'utilise le code suivant pour tester ceci:

public List<cUrlData> SoftwareData = new List<cUrlData>(); 
cUrlData urlData; 
cXml xml; 

public frmUpdater() 
{ 
    InitializeComponent(); 

    xml = new cXml("data.xml", ref SoftwareData); 
    xml.Load(); // NOT WORKING - SO I GENERATE MY OWN DATA BELOW 

    // Set up some test data to work with 
    urlData = new cUrlData(); 
    urlData.Add("Program1", 
          "Program1.exe", 
          "myDownloads", 
          "http://www.source.com/program1.exe"); 

    SoftwareData.Add(urlData); 

    urlData = new cUrlData(); 
    urlData.Add("Program2", 
          "Program2.exe", 
          "myDownloads", 
          "http://www.source.com/program2.exe"); 

    SoftwareData.Add(urlData); 

    urlData = new cUrlData(); 
    urlData.Add("Program3", 
          "Program3.exe", 
          "myDownloads", 
          "http://www.source.com/program3.exe"); 
    SoftwareData.Add(urlData); 

} 

Le problème que j'ai est de trouver un moyen fiable de convertir la liste vers et à partir d'un fichier XML. Je parcourt actuellement la liste des classes en boucle et crée manuellement le noeud xml par noeud et fait la même chose en le lisant depuis le fichier xml vers les classes mais cela est sujet aux erreurs. J'ai essayé d'obtenir le code suivant pour lire le dossier mais en vain et serais reconnaissant de quelques conseils car je suis sûr que c'est un problème de codage!

public void Load() { 
    XmlSerializer serializer = new XmlSerializer(typeof(List<cUrlData>)); 

    using (XmlReader reader = XmlReader.Create("data.xml")) 
    { 
     cUrlData myXmlClass = (cUrlData)serializer.Deserialize(reader); 
    } 
} 

Une fois chargé, je veux essayer de l'écrire dans un fichier xml. Encore une fois, de la même manière que le code ci-dessus.

Merci

+0

Vous utilisez XmlSerializer mais aucun des attributs XML, mais là encore, ils ne peuvent pas être plus nécessaires, j'oublie s'ils ont que sortir du cadre comme ils l'ont fait avec sérialisation JSON ... – jcolebrand

Répondre

4

devrait être ici une solution générale pour vous aider à démarrer sur l'enregistrement et le chargement

private void SaveData(List<cUrlData> SoftwareData) 
{ 
    try 
    { 
     using (TextWriter reader = new StreamWriter("data.xml")) 
     { 
      (new XmlSerializer(typeof(List<cUrlData>))).Serialize(reader, SoftwareData); 
     } 
    } 
    catch (Exception e) 
    { 
     MessageBox.Show(e.Message); 
    } 
} 
private List<cUrlData> LoadData() 
{ 
    List<cUrlData> mysXmlClass = null; 

    try 
    { 
     using (TextReader reader = new StreamReader("data.xml")) 
     { 
      object myXmlClass = (object)(new XmlSerializer(typeof(List<cUrlData>))).Deserialize(reader); 
      mysXmlClass = (List<cUrlData>)myXmlClass; 
     } 
    } 
    catch (Exception e) 
    { 
     MessageBox.Show(e.Message); 
    } 

    return mysXmlClass; 
} 

Il a besoin d'un peu de tided. J'ai utilisé TextReaders et StreamReaders comme je le connais.

2

Voici un couple fonctionne-je utiliser, l'espoir qu'ils aident:

public static T FromXML<T>(string xml) 
{ 
    using (StringReader stringReader = new StringReader(xml)) 
    { 
    XmlSerializer serializer = new XmlSerializer(typeof(T)); 
    return (T)serializer.Deserialize(stringReader); 
    } 
} 

public string ToXML<T>(T obj) 
{ 
    using (StringWriter stringWriter = new StringWriter(new StringBuilder())) 
    { 
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); 
    xmlSerializer.Serialize(stringWriter, obj); 
    return stringWriter.ToString(); 
    } 
} 
+0

J'aime tellement mieux. – Gauthier

3

MrNYE a la bonne idée. Voici la classe complète que nous utilisons pour sérialiser et désérialiser avec les options d'encodage.

Profitez-en!

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Xml.Serialization; 
using System.Runtime.Serialization.Formatters.Binary; 
using System.IO; 
using System.Xml; 

namespace xml.serialization 
{ 
/// <summary> 
/// Class to serialize generic objects. 
/// </summary> 
public static class ObjectSerializer 
{ 
    /// <summary> 
    /// Decode from xml string with default UTF8 encoding 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="xml"></param> 
    /// <returns></returns> 
    public static T FromString<T>(string xml) 
    { 
     Encoding e = Encoding.UTF8; 
     return FromString<T>(xml, e); 
    } 

    /// <summary> 
    /// Decode from xml string with UTF16 unicode 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="xml"></param> 
    /// <returns></returns> 
    public static T FromStringUTF16<T>(string xml) 
    { 
     Encoding e = Encoding.Unicode; 
     return FromString<T>(xml, e); 
    } 

    /// <summary> 
    /// Decode from xml string with privided encoding type 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="xml"></param> 
    /// <param name="e"></param> 
    /// <returns></returns> 
    public static T FromString<T>(string xml, Encoding e) 
    { 
     Object ret = null; 
     XmlSerializer s = new XmlSerializer(typeof(T)); 

     using (MemoryStream stream = new MemoryStream(e.GetBytes(xml))) 
     { 
      XmlTextWriter xtWriter = new XmlTextWriter(stream, e); 
      ret = s.Deserialize(stream); 
      //xtWriter.Close(); 
     } 

     return (T)ret; 
    } 

    /// <summary> 
    /// Serialize to xml with default UTF8 encoding 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="obj"></param> 
    /// <returns></returns> 
    public static string ToString<T>(T obj) 
    { 
     Encoding e = Encoding.UTF8; 
     return ToString(obj, e); 
    } 

    /// <summary> 
    /// Serialize to xml with UTF16 encoding 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="obj"></param> 
    /// <returns></returns> 
    public static string ToStringUTF16<T>(T obj) 
    { 
     Encoding e = Encoding.Unicode; 
     return ToString(obj, e); 
    } 


    /// <summary> 
    /// Serialize to xml with specified encoding 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="obj"></param> 
    /// <param name="e"></param> 
    /// <returns></returns> 
    public static string ToString<T>(T obj, Encoding e) 
    { 
     string ret = String.Empty; 
     XmlSerializer s = new XmlSerializer(typeof(T)); 

     using (MemoryStream stream = new MemoryStream()) 
     { 
      XmlTextWriter xtWriter = new XmlTextWriter(stream, e); 
      s.Serialize(xtWriter, obj); 
      xtWriter.Close(); 
      ret = e.GetString(stream.ToArray()); 
     } 

     return ret; 
    } 


    /// <summary> 
    /// Serialize to xml to to a file with default UTF8 encoding 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="obj"></param> 
    /// <param name="filePath"></param> 
    public static void ToXmlFile<T>(T obj, string filePath) 
    { 
     Encoding e = Encoding.UTF8; 
     ToXmlFile<T>(obj, filePath, e); 
    } 

    /// <summary> 
    /// Serialize to xml to to a file with specific encoding 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="obj"></param> 
    /// <param name="filePath"></param> 
    /// <param name="e"></param> 
    public static void ToXmlFile<T>(T obj, string filePath, Encoding e) 
    { 
     XmlSerializer s = new XmlSerializer(typeof(T)); 

     using (TextWriter w = new StreamWriter(filePath, false, e)) 
     { 
      s.Serialize(w, obj); 
      w.Flush(); 
      w.Close(); 
     } 
    } 

    /// <summary> 
    /// Deserialize from a file of xml useing default UTF8 encoding 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="filePath"></param> 
    /// <returns></returns> 
    public static T FromXmlFile<T>(string filePath) 
    { 

     Encoding e = Encoding.UTF8; 
     return FromXmlFile<T>(filePath, e); 

    } 

    /// <summary> 
    /// Deserialize from a file of xml useing specific encoding 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="filePath"></param> 
    /// <param name="e"></param> 
    /// <returns></returns> 
    public static T FromXmlFile<T>(string filePath, Encoding e) 
    { 
     XmlSerializer s = new XmlSerializer(typeof(T)); 
     Object ret = null; 

     using (TextReader r = new StreamReader(filePath, e)) 
     { 
      ret = s.Deserialize(r); 
      r.Close(); 
     } 

     return (T)ret; 
    } 

    } 

}