苏飞论坛
标题:
C#将DataSet转成Xml的方法(转字符串和文件两种)
[打印本页]
作者:
站长苏飞
时间:
2013-8-16 16:16
标题:
C#将DataSet转成Xml的方法(转字符串和文件两种)
方法如下,
大家看看吧,
很方便的
[code=csharp] //将DataSet转换为xml字符串
public static string ConvertDataSetToXMLFile(DataSet xmlDS, Encoding encoding)
{
MemoryStream stream = null;
XmlTextWriter writer = null;
string result = "<result>-3</result>";
try
{
stream = new MemoryStream();
//从stream装载到XmlTextReader
writer = new XmlTextWriter(stream, encoding);
//用WriteXml方法写入文件.
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + encoding.GetString(arr).Trim();
}
catch { }
finally
{
if (writer != null) writer.Close();
}
return result;
}[/code]
大家自己测试一下吧,挺好用的
下面一个是转成文件的方法
[code=csharp] //将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();
}
}[/code]
更多关于这块的功能大家可以关注下我的C#基类库,这个类我正在改进中,到时候会有更多的功能开放给大家使用
作者:
toby875187
时间:
2013-8-20 11:47
真不错啊,受教了!
作者:
Ainy
时间:
2013-9-18 17:33
Thxs 转载了
欢迎光临 苏飞论坛 (http://www.sufeinet.com/)
Powered by Discuz! X3.4