.net XmlHelper xml帮助类
using System.Data; using System.IO; using System.Xml; using System.Xml.Serialization; /// <summary> /// XML 操作基类 /// </summary> public static class XmlHelper { /// <summary> /// 将xml转为Datable /// </summary> /// <param name="xmlStr"></param> /// <returns></returns> public static DataTable Xml2DataTable(string xmlStr) { if (!string.IsNullOrEmpty(xmlStr)) { StringReader StrStream = null; XmlTextReader Xmlrdr = null; try { DataSet ds = new DataSet(); //读取字符串中的信息 StrStream = new StringReader(xmlStr); //获取StrStream中的数据 Xmlrdr = new XmlTextReader(StrStream); //ds获取Xmlrdr中的数据 ds.ReadXml(Xmlrdr); return ds.Tables[0]; } catch (Exception e) { return null; } finally { //释放资源 if (Xmlrdr != null) { Xmlrdr.Close(); StrStream.Close(); StrStream.Dispose(); } } } return null; } /// <summary> /// 将xml转为JSON /// </summary> /// <param name="xmlStr"></param> /// <returns></returns> public static string Xml2Json(string xmlStr) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlStr); string jsonText = JsonConvert.SerializeXmlNode(doc); return jsonText; } #region 反序列化 /// <summary> /// 反序列化 /// </summary> /// <param name="type">类型</param> /// <param name="xml">XML字符串</param> /// <returns></returns> public static object DESerialize(Type type, string xml) { using (StringReader sr = new StringReader(xml)) { XmlSerializer xmldes = new XmlSerializer(type); return xmldes.Deserialize(sr); } } /// <summary> /// 反序列化 /// </summary> /// <param name="type"></param> /// <param name="xml"></param> /// <returns></returns> public static object DESerialize(Type type, Stream stream) { XmlSerializer xmldes = new XmlSerializer(type); return xmldes.Deserialize(stream); } #endregion #region 序列化 /// <summary> /// 序列化 /// </summary> /// <param name="type">类型</param> /// <param name="obj">对象</param> /// <returns></returns> public static string XmlSerialize(Type type, object obj) { MemoryStream Stream = new MemoryStream(); XmlSerializer xml = new XmlSerializer(type); //序列化对象 xml.Serialize(Stream, obj); Stream.Position = 0; StreamReader sr = new StreamReader(Stream); string str = sr.ReadToEnd(); sr.Dispose(); Stream.Dispose(); return str; } #endregion 序列化 }
有错误的请多多指教,共同进步(๑•ᴗ•๑)
By听雨的人
By听雨的人