- 积分
- 40165
- 好友
- 记录
- 主题
- 帖子
- 听众
- 收听
|
方法如下,
大家看看吧,
很方便的
[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#基类库,这个类我正在改进中,到时候会有更多的功能开放给大家使用
|
|