在閱讀了大部分內容之後,我花了最近幾個小時的時間閱讀了以下代碼,看起來過時了,或者看起來似乎不起作用。使用dot.net序列化和反序列化XML#
如果對任何人的幫助是最終的工作代碼。自由隨意評論,如果能:-)
public class SerializationHelper<T> {
#region static string SerializeObject(T obj, Encoding encoding)
/// <summary>
/// Serialize an [object] to an Xml String.
/// </summary>
/// <typeparam name="T">Object Type to Serialize</typeparam>
/// <param name="obj">Object Type to Serialize</param>
/// <param name="encoding">System.Text.Encoding Type</param>
/// <returns>Empty.String if Exception, XML string if successful</returns>
/// <example>
/// // UTF-16 Serialize
/// string xml = SerializationHelper<ObjectType>SerializeObject([object], new UnicodeEncoding(false, false));
/// </example>
/// <example>
/// // UTF-8 Serialize
/// string xml = SerializationHelper<ObjectType>SerializeObject([object], Encoding.UTF8);
/// </example>
public static string SerializeObject(T obj, Encoding encoding) {
if (obj == null) { return string.Empty; }
try {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream()) {
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings() { Encoding = encoding };
using (XmlWriter writer = XmlWriter.Create(memoryStream, xmlWriterSettings)) {
xmlSerializer.Serialize(writer, obj);
}
return encoding.GetString(memoryStream.ToArray());
}
}
catch {
return string.Empty;
}
}
#endregion
#region static T DeserializeObject(string xml, Encoding encoding)
/// <summary>
/// Deserialize an Xml String to an [object]
/// </summary>
/// <typeparam name="T">Object Type to Deserialize</typeparam>
/// <param name="xml">Xml String to Deserialize</param>
/// <param name="encoding">System.Text.Encoding Type</param>
/// <returns>Default if Exception, Deserialize object if successful</returns>
/// <example>
/// // UTF-16 Deserialize
/// [object] = SerializationHelper<ObjectType>DeserializeObject(xml, Encoding.Unicode)
/// </example>
/// <example>
/// // UTF-8 Deserialize
/// [object] = SerializationHelper<ObjectType>DeserializeObject(xml, Encoding.UTF8)
/// </example>
public static T DeserializeObject(string xml, Encoding encoding) {
if (string.IsNullOrEmpty(xml)) { return default(T); }
try {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(xml))) {
// No settings need modifying here
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
using (XmlReader xmlReader = XmlReader.Create(memoryStream, xmlReaderSettings)) {
return (T)xmlSerializer.Deserialize(xmlReader);
}
}
}
catch {
return default(T);
}
}
#endregion
}
好吧,這是代碼 - 那麼你的問題是什麼?!?!你是否得到錯誤 - 如果是這樣的話:**什麼**錯誤?代碼沒有按照您期望的那樣執行?如果是這樣:你期望什麼,你會得到什麼?閱讀關於[如何在SO上提出一個好問題](http://tinyurl.com/so-hints) – 2011-02-17 05:34:58
它不是一個概述性的問題,看看它是否正確,可以改進。在閱讀了很多關於谷歌我遇到這個代碼的許多不同版本,正如我所說的大多數是使用過時的方法,有些只是明顯不工作。我也注意到,在這裏特別是很多人輸入答案,例如'我剛剛輸入了這個我的頭,它可能工作我不知道,但你明白'它是一個很好的手勢,但有時不會很高興在這裏找到代碼實際工作,經過測試,並被同意成爲其他人的最佳實踐,同時添加輸入。 – 2011-02-17 06:09:21