C# deserialize xml file to form List<T>
I have the following class and I am trying to serialize and deserialize from and to a XML file:
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;
}
}
I have been using the following code to test this out:
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",
开发者_如何学Go "http://www.source.com/program3.exe");
SoftwareData.Add(urlData);
}
The problem I am having is to find a reliable way to convert the List to and from a XML file. I currently looping through the list of classes and manually creating the xml file node by node and doing the same when reading it from the xml file to the classes but this is prone to errors. I have attempted to get the following code to read the file but to no avail and would be grateful for some advice as I am sure it is a coding problem!
public void Load() {
XmlSerializer serializer = new XmlSerializer(typeof(List<cUrlData>));
using (XmlReader reader = XmlReader.Create("data.xml"))
{
cUrlData myXmlClass = (cUrlData)serializer.Deserialize(reader);
}
}
Once loaded, I want to try and get it to write back to an xml file. Again, in a similar way to the code above.
Thank you
Here should be a general solution to get you started on saving and loading
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;
}
It does need tided up some. I used TextReaders and StreamReaders as I am familiar with those.
MrNYE has the right idea. Here is the complete class we use to Serialize and Deserialize with encoding options.
Enjoy!
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;
}
}
}
Here are a couple functions I use, hope they help:
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();
}
}
精彩评论