110,555
社区成员
发帖
与我相关
我的任务
分享
public void SingleTable2XML()
{
//Create an ODBC connection to the database. Here it is an Access file
OdbcConnection conn = new OdbcConnection("DSN=XmlDb_NorthWind");
//Create a DataSet with a name "XmlDb"
DataSet dataset = new DataSet("XmlDb");
//Create a DataAdapter to load data from original data source to the DataSet
OdbcDataAdapter adapter = new OdbcDataAdapter();
adapter.SelectCommand = new OdbcCommand("SELECT * FROM Customers", conn);
adapter.Fill(dataset, "Customers");
//Create a virtual XML document on top of the DataSet
XmlDataDocument doc = new XmlDataDocument(dataset);
//Output this XML document
doc.Save(Console.Out);
//NUnit test to confirm the result is exactly what we expect
Assert.AreEqual("XmlDb", doc.DocumentElement.LocalName);
Assert.AreEqual("Customers", doc.DocumentElement.FirstChild.LocalName);
}
//将DataSet转换为xml文件
public static void ConvertDataSetToXMLFile(DataSet xmlDS,string xmlFile)
{
MemoryStream stream = null;
XmlTextWriter writer = null;
try
{
stream = new MemoryStream();
//从stream装载到XmlTextReader
writer = new XmlTextWriter(stream, Encoding.Unicode);
//用WriteXml方法写入文件.
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
//返回Unicode编码的文本
UnicodeEncoding utf = new UnicodeEncoding();
StreamWriter sw = new StreamWriter(xmlFile);
sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sw.WriteLine(utf.GetString(arr).Trim());
sw.Close();
}
catch( System.Exception ex )
{
throw ex;
}
finally
{
if (writer != null) writer.Close();
}
}
}