當前位置:首頁 > 科技 > 正文

XML與DataTable/DataSet互轉(C#) 把數據庫中表的内容轉存為XML文件

/**////
/// 把DataSet、DataTable、DataView格式轉換成XML字符串、XML文件
///

public class DataToXml
{
/**////
/// 将DataTable對象轉換成XML字符串
///

/// DataTable對象
/// XML字符串
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 "";
}
}
/**////
/// 将DataSet對象中指定的Table轉換成XML字符串
///

/// DataSet對象
/// DataSet對象中的Table索引
/// XML字符串
public static string CDataToXml(DataSet ds, int tableIndex)
{
if (tableIndex != -1)
{
return CDataToXml(ds.Tables[tableIndex]);
}
else
{
return CDataToXml(ds.Tables[0]);
}
}
/**////
/// 将DataSet對象轉換成XML字符串
///

/// DataSet對象
/// XML字符串
public static string CDataToXml(DataSet ds)
{
return CDataToXml(ds, -1);
}
/**////
/// 将DataView對象轉換成XML字符串
///

/// DataView對象
/// XML字符串
public static string CDataToXml(DataView dv)
{
return CDataToXml(dv.Table);
}

/**////


/// 将DataSet對象數據保存為XML文件
///

/// DataSet
/// XML文件路徑
/// bool值
public static bool CDataToXmlFile(DataTable dt, string xmlFilePath)
{
if ((dt != null) && (!string.IsNullOrEmpty(xmlFilePath)))
{
string path = HttpContext.Current.Server.MapPath(xmlFilePath);
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();
//寫文件
StreamWriter sw = new StreamWriter(path);
sw.WriteLine("");
sw.WriteLine(ucode.GetString(temp).Trim());
sw.Close();
return true;
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
//釋放資源
if (XmlWt != null)
{
XmlWt.Close();
ms.Close();
ms.Dispose();
}
}
}
else
{
return false;
}
}
/**////
/// 将DataSet對象中指定的Table轉換成XML文件
///

/// DataSet對象
/// DataSet對象中的Table索引
/// xml文件路徑
/// bool]值
public static bool CDataToXmlFile(DataSet ds, int tableIndex, string xmlFilePath)
{
if (tableIndex != -1)
{
return CDataToXmlFile(ds.Tables[tableIndex], xmlFilePath);
}
else
{
return CDataToXmlFile(ds.Tables[0], xmlFilePath);
}
}
/**////
/// 将DataSet對象轉換成XML文件
///

/// DataSet對象
/// xml文件路徑
/// bool]值
public static bool CDataToXmlFile(DataSet ds, string xmlFilePath)
{
return CDataToXmlFile(ds, -1, xmlFilePath);
}
/**////
/// 将DataView對象轉換成XML文件
///

/// DataView對象
/// xml文件路徑
/// bool]值
public static bool CDataToXmlFile(DataView dv, string xmlFilePath)
{
return CDataToXmlFile(dv.Table, xmlFilePath);
}
}


/**////


/// XML形式的字符串、XML文江轉換成DataSet、DataTable格式
///

public class XmlToData
{
/**////
/// 将Xml内容字符串轉換成DataSet對象
///

/// Xml内容字符串
/// DataSet對象
public static DataSet CXmlToDataSet(string xmlStr)
{
if (!string.IsNullOrEmpty(xmlStr))
{
StringReader StrStream = null;
XmlTextReader Xmlrdr = null;
try
{
DataSet ds = new DataSet();
//讀取字符串中的信息
StrStream = new StringReader(xmlStr);
//獲取StrStream中的數據
Xmlrdr = new XmlTextReader(StrStream);
//ds獲取Xmlrdr中的數據
ds.ReadXml(Xmlrdr);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
//釋放資源
if (Xmlrdr != null)
{
Xmlrdr.Close();
StrStream.Close();
StrStream.Dispose();
}
}
}
else
{
return null;
}
}
/**////
/// 将Xml字符串轉換成DataTable對象
///

/// Xml字符串
/// Table表索引
/// DataTable對象
public static DataTable CXmlToDatatTable(string xmlStr, int tableIndex)
{
return CXmlToDataSet(xmlStr).Tables[tableIndex];
}
/**////
/// 将Xml字符串轉換成DataTable對象
///

/// Xml字符串
/// DataTable對象
public static DataTable CXmlToDatatTable(string xmlStr)
{
return CXmlToDataSet(xmlStr).Tables[0];
}
/**////
/// 讀取Xml文件信息,并轉換成DataSet對象
///

///
/// DataSet ds = new DataSet();
/// ds = CXmlFileToDataSet("/XML/upload.xml");
///

/// Xml文件地址
/// DataSet對象
public static DataSet CXmlFileToDataSet(string xmlFilePath)
{
if (!string.IsNullOrEmpty(xmlFilePath))
{
string path = HttpContext.Current.Server.MapPath(xmlFilePath);
StringReader StrStream = null;
XmlTextReader Xmlrdr = null;
try
{
XmlDocument xmldoc = new XmlDocument();
//根據地址加載Xml文件
xmldoc.Load(path);

DataSet ds = new DataSet();
//讀取文件中的字符流
StrStream = new StringReader(xmldoc.InnerXml);
//獲取StrStream中的數據
Xmlrdr = new XmlTextReader(StrStream);
//ds獲取Xmlrdr中的數據
ds.ReadXml(Xmlrdr);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
//釋放資源
if (Xmlrdr != null)
{
Xmlrdr.Close();
StrStream.Close();
StrStream.Dispose();
}
}
}
else
{
return null;
}
}
/**////


/// 讀取Xml文件信息,并轉換成DataTable對象
///

/// xml文江路徑
/// Table索引
/// DataTable對象
public static DataTable CXmlToDataTable(string xmlFilePath, int tableIndex)
{
return CXmlFileToDataSet(xmlFilePath).Tables[tableIndex];
}
/**////
/// 讀取Xml文件信息,并轉換成DataTable對象
///

/// xml文江路徑
/// DataTable對象
public static DataTable CXmlToDataTable(string xmlFilePath)
{
return CXmlFileToDataSet(xmlFilePath).Tables[0];
}
}


using System;
using System.Data;
using System.IO;
using System.Xml;
using System.Text;
// 相應C#代碼:
private string ConvertDataTableToXML(DataTable xmlDS)
{
MemoryStream stream = null;
XmlTextWriter writer = null;
try
{
stream = new MemoryStream();
writer = new XmlTextWriter(stream, Encoding.Default);
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UTF8Encoding utf = new UTF8Encoding();
return utf.GetString(arr).Trim();
}
catch
{
return String.Empty;
}
finally
{
if (writer != null) writer.Close();
}
}

private DataSet ConvertXMLToDataSet(string xmlData)
{
StringReader stream = null;
XmlTextReader reader = null;
try
{
DataSet xmlDS = new DataSet();
stream = new StringReader(xmlData);
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
return xmlDS;
}
catch (Exception ex)
{
string strTest = ex.Message;
return null;
}
finally
{
if (reader != null)
reader.Close();
}
}

把數據庫中表的内容轉存為XML文件
SqlConnection conn = new SqlConnection("server=.;database=db;uid=sa;pwd=");
SqlCommand cmd = conn.CreateCommand();
//把列的内容作為屬性,根元素名子為
cmd.CommandText = "select * from student for xml auto,root('root')";
conn.Open();
XmlReader xr = cmd.ExecuteXmlReader();
XmlDocument dd = new XmlDocument();
dd.Load(xr); ;
XmlNode xx = dd.FirstChild; //取得根元素
XmlDeclaration xd = dd.CreateXmlDeclaration("1.0", "utf-8", "yes"); //創建XML聲明
dd.InsertBefore(xd,xx); //在根元素前加入XML聲明
dd.Save(Server.MapPath("tt.config"));
conn.Close();
執行結果:




如果把上面的SqlCommand對象的CommandText改為如下:
cmd.CommandText = "select * from student for xml auto,root('root'),elements";
執行結果如下:



101
李軍

1976-02-20T00:00:00
95033


103
陸君

1974-06-03T00:00:00
95031

你可能想看:

有話要說...

取消
掃碼支持 支付碼