public class XMLHelper { #region 将xml文件转换为object对象类型 ////// 将xml文件转换为object对象类型 /// /// xml文件的路径 /// 要转换的类型的Type类型 ///public static object ConvertXMLToObject(string path, Type type) { object obj = null; using (StreamReader reader = new StreamReader(path)) { string content = reader.ReadToEnd(); if (null == content) { throw new ArgumentNullException("xml"); } if (null == type) { throw new ArgumentNullException("type"); } XmlSerializer serializer = new XmlSerializer(type); StringReader strReader = new StringReader(content); XmlReader xreader = new XmlTextReader(strReader); try { obj = serializer.Deserialize(xreader); } catch(InvalidOperationException ie) { throw new InvalidOperationException("Can not convert xml to object", ie); } finally { xreader.Close(); } return obj; } } #endregion #region 将object对象转成xml保存 /// /// 将object对象转成xml保存 /// /// 保存到xml文件的路径 /// 待转换的对象 /// xml是否缩进 true:缩进,false:不缩进 public static void SaveObjectXML(string path, object obj, bool toBeIndented=true) { if (null == obj) { throw new ArgumentNullException("obj"); } UTF8Encoding encoding = new UTF8Encoding(false); XmlSerializer serializer = new XmlSerializer(obj.GetType()); MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, encoding); writer.Formatting = toBeIndented ? Formatting.Indented : Formatting.None; try { serializer.Serialize(writer, obj); } catch (InvalidOperationException ie) { throw new InvalidOperationException("Can not convert object to xml.", ie); } finally { writer.Close(); } string xml = encoding.GetString(stream.ToArray()); using (StreamWriter swriter = new StreamWriter(path)) { swriter.Write(xml); } } #endregion }