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();
    }
  • 相关阅读:
    深入理解协程(三):async/await实现异步协程
    AES中ECB模式的加密与解密(Python3.7)
    深入理解协程(二):yield from实现异步协程
    系统结构实践期末大作业
    第7次实践作业
    第6次实践作业
    第5次实践作业
    第4次实践作业
    第3次实践作业
    第2次实践作业
  • 原文地址:https://www.cnblogs.com/xiaoerlang90/p/4126518.html
Copyright © 2011-2022 走看看