最近在做項目,這幾天遇到的問題要用到幾個資料轉換,特此記錄一下。
1.DataTable轉換為XML的三種方式
public static string DataTableToXml(this DataTable dt) { ////第一種 返回的XML字串比較乾淨,DataTable行中資料為空白的沒有寫入到XML字串中 System.IO.TextWriter tw = new System.IO.StringWriter(); dt.WriteXml(tw); return tw.ToString(); ////第二種 同第一種 MemoryStream ms = null; XmlTextWriter XmlWt = null; ms = new MemoryStream(); ////根據ms執行個體化XmlWt XmlWt = new XmlTextWriter(ms, Encoding.Unicode); ////擷取ds中的資料 dt.WriteXml(XmlWt); int count = (int)ms.Length; byte[] temp = new byte[count]; ms.Seek(0, SeekOrigin.Begin); ms.Read(temp, 0, count); ////返回Unicode編碼的文本 UnicodeEncoding ucode = new UnicodeEncoding(); string returnValue = ucode.GetString(temp).Trim(); return returnValue; ///第三種 返回的XML字串比較複雜,包括了DataTable中各個Column的定義,以及欄位類型,當然還包括DataTable行值,以及其他屬性 StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); XmlSerializer serializer = new XmlSerializer(typeof(DataTable)); serializer.Serialize(writer, dt); writer.Close(); return sb.ToString(); }
2.XML字串轉換為DataTable
public static DataSet XMLToDataTable(this string StrData) { if (!string.IsNullOrEmpty(StrData)) { XmlDocument xmlDoc = new XmlDocument(); DataSet ds = new DataSet(); try { xmlDoc.LoadXml(StrData); ds.ReadXml(GetStream(xmlDoc.OuterXml)); return ds; } catch (Exception e) { throw e; } } else { return null; } }
其中用到GetStream方法如下
public static StreamReader GetStream(this string xmlStr) { byte[] tempByte = Encoding.UTF8.GetBytes(xmlStr); MemoryStream stream = new MemoryStream(tempByte); //stream.Position = 0; StreamReader streamReader = new StreamReader(stream); return streamReader; }
上面的方法只是將XMl字串讀入到DataSet中,然後再沖DataSet中尋找先前定義過的DataTable即可。
DataTable轉換為XML字串調用即為
DataTable dt= new DataTable("Test");string XmlData=dt.DataTableToXml();
XML字串轉換為DataTable
string XmlData="此處為XML字串";DataTable dt=XmlData.XMLToDataTable().Tables["Test"];
此兩個方法暫時都用了自訂擴充方法。
以上。