通過XmlSerializer 我們可以十分簡單的將Model與XML進行轉換
官文在點這裡
幫助類
1 using System; 2 using System.Text; 3 using System.Xml.Serialization; 4 using System.IO; 5 using System.Xml; 6 7 namespace BLL 8 { 9 public class XmlHelper 10 { 11 public static T DeSerializeModels<T>(string XMLStr, string eleName) 12 { 13 XmlRootAttribute Root = new XmlRootAttribute(); 14 Root.ElementName = eleName; 15 16 XmlSerializer xs = new XmlSerializer(typeof(T), Root); 17 18 StringReader strReader = new StringReader(XMLStr); 19 System.Xml.XmlReader r = new System.Xml.XmlTextReader(strReader); 20 try 21 { 22 T Result = (T)xs.Deserialize(r); 23 return Result; 24 } 25 finally 26 { 27 strReader.Close(); 28 r.Close(); 29 } 30 } 31 32 public static string SerializeModels<T>(T Models,string eleName) 33 { 34 StringBuilder sb = new StringBuilder(); 35 StringWriter w = new StringWriter(sb); 36 37 XmlRootAttribute Root = new XmlRootAttribute(); 38 Root.ElementName = eleName; 39 40 XmlSerializer sr = new XmlSerializer(typeof(T), Root); 41 sr.Serialize(w, Models); 42 43 w.Close(); 44 45 return sb.ToString(); 46 } 47 48 private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding) 49 { 50 if (o == null) 51 throw new ArgumentNullException("o"); 52 if (encoding == null) 53 throw new ArgumentNullException("encoding"); 54 55 XmlSerializer serializer = new XmlSerializer(o.GetType()); 56 57 XmlWriterSettings settings = new XmlWriterSettings(); 58 settings.Indent = true; 59 settings.NewLineChars = "\r\n"; 60 settings.Encoding = encoding; 61 settings.IndentChars = " "; 62 63 using (XmlWriter writer = XmlWriter.Create(stream, settings)) 64 { 65 serializer.Serialize(writer, o); 66 writer.Close(); 67 } 68 } 69 70 /// <summary> 71 /// 將一個對象序列化為XML字符串 72 /// </summary> 73 /// <param name="o">要序列化的對象</param> 74 /// <param name="encoding">編碼方式</param> 75 /// <returns>序列化產生的XML字符串</returns> 76 public static string XmlSerialize(object o, Encoding encoding) 77 { 78 using (MemoryStream stream = new MemoryStream()) 79 { 80 XmlSerializeInternal(stream, o, encoding); 81 82 stream.Position = 0; 83 using (StreamReader reader = new StreamReader(stream, encoding)) 84 { 85 return reader.ReadToEnd(); 86 } 87 } 88 } 89 90 /// <summary> 91 /// 將一個對象序列化為XML字符串 92 /// </summary> 93 /// <param name="o">要序列化的對象</param> 94 /// <returns>序列化產生的XML字符串</returns> 95 public static string XmlSerialize(object o) 96 { 97 return XmlSerialize(o, Encoding.UTF8); 98 } 99 100 /// <summary> 101 /// 將一個對象按XML序列化的方式寫入到一個文件 102 /// </summary> 103 /// <param name="o">要序列化的對象</param> 104 /// <param name="UploadPath">保存文件路徑</param> 105 /// <param name="encoding">編碼方式</param> 106 public static void XmlSerializeToFile(object o, string path, Encoding encoding) 107 { 108 if (string.IsNullOrEmpty(path)) 109 throw new ArgumentNullException("path"); 110 111 using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write)) 112 { 113 XmlSerializeInternal(file, o, encoding); 114 } 115 } 116 117 /// <summary> 118 /// 將一個對象按XML序列化的方式寫入到一個文件 119 /// </summary> 120 /// <param name="o">要序列化的對象</param> 121 /// <param name="UploadPath">保存文件路徑</param> 122 public static void XmlSerializeToFile(object o, string path) 123 { 124 XmlSerializeToFile(o, path, Encoding.UTF8); 125 } 126 127 /// <summary> 128 /// 從XML字符串中反序列化對象 129 /// </summary> 130 /// <typeparam name="T">結果對象類型</typeparam> 131 /// <param name="s">包含對象的XML字符串</param> 132 /// <param name="encoding">編碼方式</param> 133 /// <returns>反序列化得到的對象</returns> 134 public static T XmlDeserialize<T>(string s, Encoding encoding) 135 { 136 if (string.IsNullOrEmpty(s)) 137 throw new ArgumentNullException("s"); 138 if (encoding == null) 139 throw new ArgumentNullException("encoding"); 140 141 XmlSerializer xs = new XmlSerializer(typeof(T)); 142 using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s))) 143 { 144 using (StreamReader sr = new StreamReader(ms, encoding)) 145 { 146 return (T)xs.Deserialize(sr); 147 } 148 } 149 } 150 151 /// <summary> 152 /// 從XML字符串中反序列化對象 153 /// </summary> 154 /// <typeparam name="T">結果對象類型</typeparam> 155 /// <param name="s">包含對象的XML字符串</param> 156 /// <returns>反序列化得到的對象</returns> 157 public static T XmlDeserialize<T>(string s) 158 { 159 return XmlDeserialize<T>(s, Encoding.UTF8); 160 } 161 162 /// <summary> 163 /// 讀入一個文件,並按XML的方式反序列化對象。 164 /// </summary> 165 /// <typeparam name="T">結果對象類型</typeparam> 166 /// <param name="UploadPath">文件路徑</param> 167 /// <param name="encoding">編碼方式</param> 168 /// <returns>反序列化得到的對象</returns> 169 public static T XmlDeserializeFromFile<T>(string path, Encoding encoding) 170 { 171 if (string.IsNullOrEmpty(path)) 172 throw new ArgumentNullException("path"); 173 if (encoding == null) 174 throw new ArgumentNullException("encoding"); 175 176 string xml = File.ReadAllText(path, encoding); 177 return XmlDeserialize<T>(xml, encoding); 178 } 179 180 /// <summary> 181 /// 讀入一個文件,並按XML的方式反序列化對象。 182 /// </summary> 183 /// <typeparam name="T">結果對象類型</typeparam> 184 /// <param name="UploadPath">文件路徑</param> 185 /// <returns>反序列化得到的對象</returns> 186 public static T XmlDeserializeFromFile<T>(string path) 187 { 188 return XmlDeserializeFromFile<T>(path, Encoding.UTF8); 189 } 190 } 191 } 工具類
同時也可以通過設置Model的特性,靈活的控制序列化
using System.Xml.Serialization; using System; using System.Collections.Generic; namespace Model { /// <summary> /// 節點名是EleTeacher /// </summary> [Serializable] [XmlType("EleTeacher")] public class Teacher { [XmlElement(ElementName = "user")] public string AuthorID { set; get; } [XmlIgnore] public string Content { set; get; } [XmlText] public string Value { set; get; } [XmlArray("students")] public List<Student> sds { set; get; } } [Serializable] public class Student { [XmlAttribute(AttributeName = "id")] public string ID { set; get; } [XmlText] public string Name { set; get; } } } Model
把我的序列化和反序列化方法發給你吧,你替換一下下面的雙引號:
#region XML相關的靜態方法
/// <summary>
/// 使用XmlSerializer序列化對象
/// </summary>
/// <typeparam name=“T“>需要序列化的對象類型,必須聲明[Serializable]特征</typeparam>
/// <param name=“obj“>需要序列化的對象</param>
public static string XmlSerialize<T>(T obj)
{
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(ms, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
/// <summary>
/// 使用XmlSerializer反序列化對象
/// </summary>
/// <param name=“xmlOfObject“>需要反序列化的xml字符串</param>
public static T XmlDeserialize<T>(string xmlOfObject) where T : class
{
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sr = new StreamWriter(ms, Encoding.UTF8))
{
sr.Write(xmlOfObject);
sr.Flush();
ms.Seek(0, SeekOrigin.Begin);
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(ms) as T;
}
}
}
#endregion...余下全文>>
[XmlRootAttribute("Extensiondata", IsNullable = false)]
public class Extensiondata
{
public string MagnetPullStrength;
public string MagnetGrade;
public string VisibleCustomerID;
}
XmlSerializer serializer = new XmlSerializer(typeof(Extensiondata));
TextWriter writer = new StreamWriter(CommonLogic.SafeMapPath("images\\po.xml"));
Extensiondata po = new Extensiondata();
po.MagnetPullStrength = TextBox1.Text;
po.MagnetGrade = TextBox2.Text;
po.VisibleCustomerID = TextBox3.Text;
serializer.Serialize(writer, po);
writer.Close();