日期:2014-05-17 浏览次数:20879 次
/// <summary> /// 将DataTable对象转换成XML字符串 /// </summary> /// <param name="dt">DataTable对象</param> /// <returns>XML字符串</returns> public static string CDataToXml(DataTable dt) { if (dt != null) { MemoryStream ms = null; XmlTextWriter XmlWt = null; try { 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; } catch (System.Exception ex) { throw ex; } finally { //释放资源 if (XmlWt != null) { XmlWt.Close(); ms.Close(); ms.Dispose(); } } } else { return ""; } } public string GetXmlString() { DataTable dt = new DataTable(); dt.TableName = "filepath"; dt.Columns.Add("id", typeof(int)); dt.Columns.Add("name", typeof(string)); dt.Rows.Add(1, "a"); dt.Rows.Add(2, "b"); dt.Rows.Add(3, "c"); dt.Rows.Add(4, "d"); dt.Rows.Add(5, "e"); return CDataToXml(dt); /* 得到的结果是这个样子的: <DocumentElement> <filepath><id>1</id><name>a</name></filepath> <filepath><id>2</id><name>b</name></filepath> <filepath><id>3</id><name>c</name></filepath> <filepath><id>4</id><name>d</name></filepath> <filepath><id>5</id><name>e</name></filepath> </DocumentElement> */ /* 我想要的结果是这个样子 <?xml version="1.0" encoding="utf-8"?> <root> <filepath id="1" name="a"/> <filepath id="2" name="b"/> <filepath id="3" name="c"/> <filepath id="4" name="d"/> <filepath id="5" name="e"/> </root> */ }