//将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;
}
//将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();
}
}
转载自:https://blog.51cto.com/aonaufly/1298823