C# DataTable与XML互转
将DataTable对象转换成XML字符串
C# 全选
/// <summary>
/// 将DataTable对象转换成XML字符串
/// </summary>
/// <returns>XML字符串</returns>
public static string ToXml(DataTable dt)
{
if (dt == null) return string.Empty;
MemoryStream ms = null;
System.Xml.XmlTextWriter xmlWriter = null;
string tableName = dt.TableName;
dt.TableName = String.IsNullOrWhiteSpace(tableName) ? "dt2xml" : tableName;
try
{ // 将DataTable转换为XML格式,并写入MemoryStream
ms = new MemoryStream();
xmlWriter = new XmlTextWriter(ms, Encoding.Unicode);
dt.WriteXml(xmlWriter, XmlWriteMode.WriteSchema);
xmlWriter.Flush();
// 重置MemoryStream的位置,以便读取其内容
ms.Position = 0;
// 从MemoryStream读取XML内容
StreamReader reader = new StreamReader(ms);
string xmlContent = reader.ReadToEnd();
// 关闭reader和memoryStream
reader.Close();
ms.Close();
xmlWriter.Close();
return xmlContent;
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
//释放资源
if (xmlWriter != null) xmlWriter.Close();
if (ms != null) ms.Close();
}
}
将xml内容转换为dataset
C# 全选
/// <summary>
/// 将xml内容转换为dataset
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static DataSet FromXml(string xml)
{
StringReader stream = null;
XmlTextReader reader = null;
try
{
DataSet xmlDS = new DataSet();
stream = new StringReader(xml);
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
reader.Close();
return xmlDS;
}
catch (System.Exception ex)
{
reader.Close();
throw ex;
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网