DataRow dr = new DataRow();//数据行 DataSet ds = new DataSet();
string xml = ds.GetXml();
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\1.xml", false, Encoding.UTF8))
{
sw.Write(xml);
}大家好,我有一行数据dr,我想把他转换为一个xml文件来处理。
DataSet 有GetXml(),那DataRow有什么?
如果是自己手动来生成,字段太多,累死了!
/// 将DataSet对象数据保存为XML文件
/// </summary>
/// <param name="dt">DataSet</param>
/// <param name="xmlFilePath">XML文件路径</param>
/// <returns>bool值</returns>
public static bool CDataToXmlFile(DataTable dt, string xmlFilePath)
{
if ((dt != null) && (!string.IsNullOrEmpty(xmlFilePath)))
{
//string path =System.Windows.Forms.Application.StartupPath + System.Configuration.ConfigurationManager.AppSettings["flow"]+ xmlFilePath; string path = xmlFilePath; MemoryStream ms = null; XmlTextWriter XmlWt = null; try
{
ms = new MemoryStream(); //根据ms实例化XmlWt XmlWt = new XmlTextWriter(ms, Encoding.Unicode); //获取ds中的数据
dt.WriteXml(XmlWt); int count = (int)ms.Length; byte[] temp = new byte[count]; ms.Seek(0, SeekOrigin.Begin); ms.Read(temp, 0, count); UnicodeEncoding ucode = new UnicodeEncoding(); //返回Unicode编码的文本
StreamWriter sw = new StreamWriter(path); //写文件 sw.WriteLine("<?xml version='1.0' encoding='utf-8'?>"); sw.WriteLine(ucode.GetString(temp).Trim()); sw.Close(); return true;
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
//释放资源
if (XmlWt != null)
{
XmlWt.Close(); ms.Close(); ms.Dispose();
}
}
}
else
{
return false;
}
}