1.DataTable轉XML 編碼
#region DataTableToXml /// <summary> /// 將DataTable對象轉換成XML字符串 /// </summary> /// <param name="ds">DataSet對象</param> /// <returns>XML字符串</returns> public static string DataTableToXml(DataTable dt,string sName) { if (dt != null) { MemoryStream ms = null; XmlTextWriter XmlWt = null; try { ms = new MemoryStream(); //根據ms實例化XmlWt XmlWt = new XmlTextWriter(ms, System.Text.Encoding.Unicode); //獲取ds中的數據 dt.TableName = Sql.IsEmptyString(sName) ? "dt2xml" : sName; dt.WriteXml(XmlWt, XmlWriteMode.WriteSchema); int count = (int)ms.Length; byte[] temp = new byte[count]; ms.Seek(0, SeekOrigin.Begin); ms.Read(temp, 0, count); //返回Unicode編碼的文本 System.Text.UnicodeEncoding ucode = new System.Text.UnicodeEncoding(); string returnValue = ucode.GetString(temp).Trim(); return returnValue; } catch (System.Exception ex) { throw ex; } finally { //釋放資源 if (XmlWt != null) { XmlWt.Close(); ms.Close(); ms.Dispose(); } } } else { return ""; } } #endregion
2.XML轉DataSetcode
#region Xml To DataSet public static DataSet XmlToDataSet(string xmlString) { XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(xmlString); StringReader stream = null; XmlTextReader reader = null; try { DataSet xmlDS = new DataSet(); stream = new StringReader(xmldoc.InnerXml); reader = new XmlTextReader(stream); xmlDS.ReadXml(reader); reader.Close(); return xmlDS; } catch (System.Exception ex) { reader.Close(); throw ex; } } #endregion