首页 > 代码库 > C# datatable 与 xml文件之间的转换
C# datatable 与 xml文件之间的转换
/// <summary>/// datatable转XML文件/// </summary>/// <param name="dtTable"></param>/// <param name="strXMLPath"></param>/// <returns></returns>public bool DataTableToXML(DataTable dtTable, string strXMLPath){MemoryStream stream = null;XmlTextWriter writer = null;DataSet ds=new DataSet ();ds.Tables.Add(dtTable.Copy());StreamWriter sw = null;try{stream = new MemoryStream();writer = new XmlTextWriter(stream, Encoding.UTF8);ds.WriteXml(writer, XmlWriteMode.WriteSchema);int nCount = (int)stream.Length;byte[] arr = new byte[nCount];stream.Seek(0, SeekOrigin.Begin);stream.Read(arr, 0, nCount);UTF8Encoding utf = new UTF8Encoding();string strContent = utf.GetString(arr).Trim();sw = new StreamWriter(strXMLPath);sw.Write(strContent);return true;}catch (System.Exception vErr){MessageBox.Show(vErr.Message);return false;}finally{if (writer != null){writer.Close();}if (sw != null){sw.Close();}}}/// <summary>/// 读取XML转datatable/// </summary>/// <param name="strXMLPath"></param>/// <returns></returns>public DataTable XMLToDataTable(string strXMLPath){StringReader stream = null;XmlTextReader reader = null;StreamReader sr = null;try{if (strXMLPath.Length <= 0){return new DataTable();}sr = new StreamReader(strXMLPath);string strXmlContent = sr.ReadToEnd();stream = new StringReader(strXmlContent);reader = new XmlTextReader(stream);DataSet ds = new DataSet();ds.ReadXml(reader);return ds.Tables[0];}catch (System.Exception vErr){MessageBox.Show(vErr.Message);}finally{if (sr != null)sr.Close();if (reader != null)reader.Close();}return new DataTable();}
C# datatable 与 xml文件之间的转换
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。