DataTable与XML字符串互转
时间:2011-06-13 来源:剑指苍穹怒骂天
将DataTable对象转换成XML字符串
1 /// <summary>
2 /// 将DataTable对象转换成XML字符串
3 /// </summary>
4 /// <param name="xmlDT">DataTable对象</param>
5 /// <returns>XML字符串</returns>
6 private string ConvertDataTableToXML(DataTable xmlDT)
7 {
8 MemoryStream stream = null;
9 XmlTextWriter writer = null;
10 try
11 {
12 stream = new MemoryStream();
13 writer = new XmlTextWriter(stream, Encoding.Default);//根据stream实例化writer
14 xmlDT.TableName = "dt";
15 xmlDT.WriteXml(writer);//获取DataTable中的数据
16 int count = (int)stream.Length;
17 byte[] arr = new byte[count];
18 stream.Seek(0, SeekOrigin.Begin);
19 stream.Read(arr, 0, count);
20 return Encoding.GetEncoding("gb2312").GetString(arr).Trim();//解决中文乱码问题
21 //UTF8Encoding utf = new UTF8Encoding();
22 //return utf.GetString(arr).Trim();
23 }
24 catch (Exception e)
25 {
26 throw e;
27 }
28 finally
29 {
30 if (writer != null)
31 writer.Close();
32 }
33 }
将Xml字符串转换成DataTable对象
1 /// <summary>
2 /// 将Xml字符串转换成DataTable对象
3 /// </summary>
4 /// <param name="xmlData">Xml字符串</param>
5 /// <returns>DataTable对象</returns>
6 private DataTable ConvertXMLToDataTable(string xmlData)
7 {
8 StringReader stream = null;
9 XmlTextReader reader = null;
10 try
11 {
12 DataSet xmlDS = new DataSet();
13 stream = new StringReader(xmlData);//读取字符串中的信息
14 reader = new XmlTextReader(stream);//获取stream中的数据
15 xmlDS.ReadXml(reader);//DataSet获取Xmlrdr中的数据
16 return xmlDS.Tables[0];
17 }
18 catch (Exception e)
19 {
20 throw e;
21 }
22 finally
23 {
24 if (reader != null)
25 reader.Close();
26 }
27 }
相关阅读 更多 +