zoukankan      html  css  js  c++  java
  • C# datatable 与 xml文件之间的转换

    /// <summary>
    /// datatable转XML文件
    /// </summary>
    /// <param name="dtTable"></param>
    /// <param name="strXMLPath"></param>
    /// <returns></returns>
    public bool DataTableToXML(DataTable dtTable, string strXMLPath)
    {
    MemoryStream stream = null;
    XmlTextWriter writer = null;
    DataSet ds=new DataSet ();
    ds.Tables.Add(dtTable.Copy());
    StreamWriter sw = null;
    try
    {
    stream = new MemoryStream();
    writer = new XmlTextWriter(stream, Encoding.UTF8);
    ds.WriteXml(writer, XmlWriteMode.WriteSchema);
    int nCount = (int)stream.Length;
    byte[] arr = new byte[nCount];
    stream.Seek(0, SeekOrigin.Begin);
    stream.Read(arr, 0, nCount);
    UTF8Encoding utf = new UTF8Encoding();
    string strContent = utf.GetString(arr).Trim();
    sw = new StreamWriter(strXMLPath);
    sw.Write(strContent);
    
    return true;
    }
    catch (System.Exception vErr)
    {
    MessageBox.Show(vErr.Message);
    return false;
    }
    finally
    {
    if (writer != null)
    {
    writer.Close();
    }
    if (sw != null)
    {
    sw.Close();
    }
    }
    }
    /// <summary>
    /// 读取XML转datatable
    /// </summary>
    /// <param name="strXMLPath"></param>
    /// <returns></returns>
    public DataTable XMLToDataTable(string strXMLPath)
    {
    StringReader stream = null;
    XmlTextReader reader = null;
    StreamReader sr = null;
    try
    {
    if (strXMLPath.Length <= 0)
    {
    return new DataTable();
    }
    sr = new StreamReader(strXMLPath);
    string strXmlContent = sr.ReadToEnd();
    stream = new StringReader(strXmlContent);
    reader = new XmlTextReader(stream);
    DataSet ds = new DataSet();
    ds.ReadXml(reader);
    return ds.Tables[0];
    }
    catch (System.Exception vErr)
    {
    MessageBox.Show(vErr.Message);
    }
    finally
    {
    if (sr != null)
    sr.Close();
    if (reader != null)
    reader.Close();
    }
    return new DataTable();
    }
  • 相关阅读:
    django实战-XX学院选课系统
    django学习记录
    WEB前端--CSS样式优先级
    python中__str__和__repr__的区别
    转载--SqlAlchemy ORM 学习
    转载---Python模块学习optparse 处理命令行参数
    转载--Python之路,进程、线程、协程篇(原文地址:http://www.cnblogs.com/alex3714/articles/5230609.html)
    python学习---模拟人生
    python学习---购物商场与ATM
    解决"回调地狱"的发展过程
  • 原文地址:https://www.cnblogs.com/xiaoerlang90/p/4126518.html
Copyright © 2011-2022 走看看