POCO:
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace CYFang
{
///https://stackoverflow.com/questions/29085381/mapping-xml-to-classes-in-c-sharp
/// <summary>
/// Config
/// </summary>
[Serializable]
[XmlRoot(ElementName = "list")]
public class Config
{
/// <summary>
/// StringWriterWithUTF8Encoding
/// </summary>
private sealed class StringWriterWithUTF8Encoding : StringWriter
{
/// <summary>
/// UTF8Encoding
/// </summary>
private UTF8Encoding UTF8Encoding { get { return new UTF8Encoding(); } }
/// <summary>
/// Encoding
/// </summary>
public override Encoding Encoding => UTF8Encoding;
}
/// <summary>
/// VMWare path
/// </summary>
[XmlElement(ElementName = "VMwarePath")]
public String VMwarePath { get; set; }
/// <summary>
/// Restart Time
/// </summary>
[XmlElement(ElementName = "RestartTime")]
public String RestartTime { get; set; }
/// <summary>
/// Constructor
/// </summary>
public Config(){}
/// <summary>
/// Save string to xml
/// </summary>
public void Save() => File.WriteAllText(MyPath.ConfigPath, Serialize(this), Encoding.UTF8);
/// <summary>
/// Read xml to string
/// </summary>
/// <returns></returns>
private static string Read() =>(!MyPath.ConfigFileExists)? string.Empty: File.ReadAllText(MyPath.ConfigPath, Encoding.UTF8);
/// <summary>
/// Serialize
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private string Serialize(object obj)
{
var serializer = new XmlSerializer(obj.GetType());
using (var stringWriter = new StringWriterWithUTF8Encoding { })
{
serializer.Serialize(stringWriter, obj);
return stringWriter.ToString();
}
}
/// <summary>
/// Deserialize
/// </summary>
/// <param name="serializedObj"></param>
/// <returns></returns>
public static Config Deserialize()
{
string str = Read();
if (str.Equals(string.Empty))
return null;
var serializer = new XmlSerializer(typeof(Config));
using (var stringReader = new StringReader(str))
{
using (var xmlTextReader = new XmlTextReader(stringReader))
{
var config = (Config)serializer.Deserialize(xmlTextReader);
return config;
}
}
}
}
}
Main:
using CYFang;
using System;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MyPath.CreateConfigFolder();
var config = new Config {
RestartTime = "aaa",
VMwarePath = "aaaa"
};
config.Save();
config = Config.Deserialize();
Console.WriteLine("{0} {1}", config.RestartTime, config.VMwarePath);
}
}
}
參考資料:
https://stackoverflow.com/questions/29085381/mapping-xml-to-classes-in-c-sharp